Unity 3 DでC#呼び出しC++ダイナミックライブラリまとめ

1988 ワード

ダイナミックライブラリはC++とOpenCVで書かれています.
このように分類することができます
1.次のコードのMotionDetectの4番目のパラメータのような一般的な値伝達.
2.転送参照、MotionDetectの3番目のパラメータ、nNumがダイナミックライブラリに転送された後に値を割り当ててから転送します.
3.1つの構造体、MotionDetectの2番目のパラメータを参照して、ここでは実は1つの構造体の配列を伝えて、具体的にはrefを加えたパラメータのように本当にできません;
4.メモリが割り当てられた変数を渡すには、GCHandleを使用する必要があります.C#はメモリを自動的に回収できるため、GCHandleはここでメモリ空間Pinを住み、C++ダイナミックライブラリに渡してから手動でリソースを回収する役割を果たします.
using UnityEngine;
using System.Collections;
using System.Runtime.InteropServices;

public class D : MonoBehaviour 
{
	struct Color_32
	{
		public byte r;
		public byte g;
		public byte b;
		public byte a;
	}
	Color_32[]  imageDataResult;
	
	GCHandle pixelsHandle;
	
	[DllImport("MotionDetectionDll")]
	private static extern bool MotionDetect( System.IntPtr colors, Color_32[] imageDataResult, ref int nNum, int nChannels );
	
	void Start()
    {
		imageDataResult = new Color_32[128*128];
	}
	
	void Update () 
	{
		int nNum = 0;
		pixelsHandle = GCHandle.Alloc(pixels, GCHandleType.Pinned);
		bool wfDf = MotionDetect( pixelsHandle.AddrOfPinnedObject(), imageDataResult, ref nNum, 4 );
		pixelsHandle.Free();
	}
}

C++にはこう書いてあります
//            
#include "stdafx.h"
struct Color_32
{
	byte r;
	byte g;
	byte b;
	byte a;
};
extern "C" _declspec(dllexport) bool MotionDetect ( char* imageData, Color_32 imageDataResult[], int *nNum, int nChannels );

// CPP   
extern "C" _declspec(dllexport) bool MotionDetect ( char* imageData, Color_32 imageDataResult[], int *nNum, int nChannels )
{
	IplImage* imgSrc = cvCreateImageHeader(cvSize(width, height), IPL_DEPTH_8U, 4);
	if(!imgSrc)
	{
		return false;
	}
	cvSetData( imgSrc, imageData, imgSrc->widthStep );
	
	......
	
	for ( int i=0; i< ......; i++ )
	{
		imageDataResult[i].r = ......;
		imageDataResult[i].g = ......;
		imageDataResult[i].b = ......;
		imageDataResult[i].a = ......;
	}
	
	......
	
	*nNum = 5;
	nChannels = 4;
}