c# - 如何将 C++ 结构数组编组为 C#
问题描述
我打算将一个 c++ struct 数组编组到 c# 中,我尝试了很多方法来做到这一点,但是函数返回的数组一直是一个空数组。我不知道问题是什么。这是我的 C++ 代码:
# include<iostream>
typedef struct
{
float x, y, z;
}cfloat3;
extern "C" __declspec(dllexport) cfloat3* Test();
extern "C" __declspec(dllexport) void freeMemory(cfloat3 * a);
cfloat3* Test()
{
cfloat3* a = new cfloat3[5];
for (int i = 0; i < 5; i++)
{
a[i].x = 1;
a[i].y = 1;
a[i].z = 1;
}
return a;
}
void freeMemory(cfloat3* a)
{
delete[] a;
}
这是我的 C# 代码
namespace ConsoleApp3
{
[StructLayout(LayoutKind.Sequential)]
struct cfloat3
{
public float x, y, z;
}
class Program
{
[DllImport("Dll1.dll", EntryPoint = "Test")]
public static extern IntPtr Test();
[DllImport("Dll1.dll", EntryPoint = "freeMemory")]
public static extern void freeMemory( IntPtr a);
static void Main(string[] args)
{
int length = 5;
int size = Marshal.SizeOf(typeof(cfloat3)) * length;
IntPtr pBuff = Marshal.AllocHGlobal(size);
cfloat3[] pClass = new cfloat3[length];
pBuff=Test();
IntPtr[] bb = new IntPtr[length];
Marshal.Copy(pBuff, bb, 0, length);
for (int i = 0; i < length; i++)
{
pClass[i] = (cfloat3)Marshal.PtrToStructure(bb[i],typeof(cfloat3));
Console.WriteLine(pClass[i].x);
Console.WriteLine(pClass[i].y);
Console.WriteLine(pClass[i].z);
}
Marshal.FreeHGlobal(pBuff);
Console.ReadKey();
}
}
}
运行这个程序,我得到“System.AccessViolationException:试图读取或写入受保护的内存。这通常表明其他内存已损坏。”
解决方案
您需要在每个字段中使用MarshalAs
注释,SizeConst
并将 C# 的返回类型单独映射到 c++ 结构和返回类型
请参考这个答案Marshaling C++ struct to C#
推荐阅读
- nginx - 位置中的 Nginx 问号移动到另一个位置
- java - Micronaut 配置未发出 JWT 刷新令牌
- mapbox-android - 找不到 mapbox vision sdk 依赖项
- types - 所有估计器都应该实现 fit 和 transform,或者可以是“drop”或“passthrough”说明符
- python - Python Pandas:根据后一个值更改前一行的值(在分组/分区数据框中)
- python - 在不丢失基数信息的情况下对 TensorFlow 数据集进行窗口化?
- ibm-midrange - 在 AS400 中显示程序消息
- forms - Vee Validate Nuxt JS 属性或方法“必需”未在实例上定义,但在渲染期间引用
- reactjs - 测试函数是否只调用一次的首选方法是什么?
- javascript - 使用 html 代码从变量中获取所有 id