首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >将数据从Unity3D传递到C++ dll,反之亦然

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

Stack Overflow用户
提问于 2016-04-21 15:05:23
回答 1查看 3.4K关注 0票数 3

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

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

有人能向我解释如何实现这一点吗?你还能发布一个示例代码吗?

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

EN

回答 1

Stack Overflow用户

回答已采纳

发布于 2016-04-22 18:25:37

我刚刚找到了解决方案() :)

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

Unity3D(C#)中的代码:

代码语言:javascript
复制
        //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#的传递数据重建图像:

代码语言:javascript
复制
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)..
}
票数 3
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/36773599

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档