将数据从 Unity3D 传递到 C++ dll,反之亦然
Passing data from Unity3D to C++ dll and vice versa
我目前正在写我的论文(计算机科学硕士),这是一个使用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)..
}
相关文章:
- 挂起和取消挂起一个文件DLL
- std::threads可以从Windows DLL中的全局变量创建/销毁吗?
- 导入库可以跨dll版本工作吗
- 从C++dll访问C#中的一行主要参数
- 链接到自行创建的dll失败
- 为什么使用 P/Invoke 调用 dll 时,某些计算机中的 LoadLibrary 失败?
- 在调用FreeLibrary后,释放动态链接到具有相同版本的CRT堆的DLL的内存
- 如何指定我希望我的LIB链接到的DLL文件?-Visual Studio 2019
- 如何将图像传输到c++(dll)中的缓冲区,然后在c#的缓冲区中读/写
- C++:将外部库链接到dll库
- 在 Windows 上,是否可以让 dll 在不使用 PATH 环境变量的情况下在另一个文件夹中查找依赖项?
- 不同的Visual Studio版本中缺少.dll
- 从DLL中删除类的实例
- 如何包装第三方DLL在R中使用
- 使用c#访问c++dll中带有char*参数的函数时发生AccessViolationException
- 系统.将数组移交给c#中动态加载的c++DLL时发生AccessViolationException
- 为什么导入Mixed native/CLR lib.dll的本机C++应用程序没有在Mixed lib.dll中的外部变
- 当我使用 C++ 中的 C# dll 来使用 Selenium 时,存在异常处理问题
- Python ctypes:不会按预期加载 dll
- 在 C++/CLI 中将 .NET 事件从一个 DLL 引发到另一个 DLL