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

Passing data from Unity3D to C++ dll and vice versa

本文关键字:C++ dll 反之亦然 数据 Unity3D      更新时间:2023-10-16

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

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

谁能向我解释如何实现这一目标,你也可以发布一个示例代码吗?

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

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

首先,我需要将我的 C# 垫(帧)转换为字节数组。然后我创建了一个指针,以指向字节地址数组(即图像数据)。在此之后,我调用了 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)..
}