c++ - 将数据从 Unity3D 传递到 C++ dll,反之亦然

标签 c++ opencv unity3d marshalling augmented-reality

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

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

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

编辑: 我正在使用的 Unity3D 资源可以在这里找到:OpenCV for Unity3D

最佳答案

我刚刚找到了解决方案(哦,是啊啊啊啊啊):)

首先,我需要将我的 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)..
}

关于c++ - 将数据从 Unity3D 传递到 C++ dll,反之亦然,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/36773599/

相关文章:

c++ - 如何解决这个 : "cannot convert parameter 1 from ' const GLdouble' to 'const GLdouble *"?

c++ - 如何使用 dladdr 获取 gnu 间接函数的名称?

c# - 地形地面,城市中的草地和雪地 : Skylines

C++ 使用 RAII 创建数组

opencv - 在不使用 split() 函数的情况下拆分 BGR 矩阵

opencv - 使用来自 cv2.VideoWriter 的 write() 后的错误/空视频

c++ - 无法从终端编译c++文件

ios - Xcode 6 上的估计 App Store 大小显示出巨大的大小(Unity iOS 导出)

c# - 如何检测 child 碰撞其他碰撞器?

c++ - 是否允许编译器优化堆内存分配?