将数据从Unity3D传递到C ++ DLL,反之亦然

时间:2016-04-21 15:05:23

标签: c++ opencv unity3d marshalling augmented-reality

我目前正在研究我的论文(MSc Computer Science),这是一个使用与Unity3D集成的OpenCV C ++(用于渲染部分)的增强现实项目。为了将OpenCV与Unity3D集成,我将OpenCV(c ++)代码导出为dll,然后我在Unity3D中导入该dll以访问dll的方法等。此外,大学给了我一些钱购买OpenCV对于Unity(它使用OpenCV for Java在C#中实现),我也在Unity3D中使用它。问题是,它不支持SURF特征提取器,这就是为什么我没有使用该资产直接将C ++代码实现到C#中。

所以我想将一个帧(Mat)从Unity3D(C#)传递给C ++ dll,然后进行一些计算,然后返回一些Mat对象,例如旋转矩阵,平移向量和相机姿势。最重要的是我不知道如何将Unity框架从Unity3D传递到C ++ DLL。

任何人都可以向我解释如何实现这一目标,还可以发布示例代码吗?

编辑我可以在此处找到我正在使用的Unity3D资产:OpenCV for Unity3D

1 个答案:

答案 0 :(得分:2)

我刚刚找到解决方案(ohh yeahhhhhhhh):)

首先,我需要将C#Mat(帧)转换为字节数组。然后我创建了一个指针,以指向字节数组地址(这是图像数据)。在此之后,我调用了C ++ dll方法并将指针作为参数(以及图像的宽度和高度)传递。最后在C ++ DLL中,我使用C#中的字节数组重构了C ++ Mat。

Unity3D中的代码(C#):

        //frame is the C# Mat and byte_array our array of byes

        //to initialize the size of our byte array (image pixels * channels)
        byte_array= new byte[frame.cols () * frame.rows () * frame.channels ()];
        //copy the frame data to our array
        Utils.copyFromMat (frame,byte_array);
        //initialize a pointer with the apropriate size (array size)
        IntPtr pointer = Marshal.AllocHGlobal(byte_array.Length);
        Marshal.Copy (byte_array, 0, pointer , byte_array.Length);
        //here i call the C++ method (I imported a C++ dll)
        myCplusplusMethod(pointer ,frame.height(),frame.width());
        //free the pointer
        Marshal.FreeHGlobal(pointer );

现在,为了使用来自C#的传递数据在C ++中重建图像:

void myCplusplusMethod(unsigned char* data,int height,int width){
     //btw you have to get the correct type. In my situation I use debug from C# and I found out that my image is CV_8UC3 type.
     Mat constructed= Mat(height, width, CV_8UC3, data);
     //..do whatever using the image.. (calculations , etc)..
}
相关问题