[英]How to marshall C++ struct array into C#
我計划將一個 c++ 結構數組編組到 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: Attempted to read or write protected memory。這通常表明其他內存已損壞。”
您需要在每個字段中使用帶有SizeConst
MarshalAs
注釋, SizeConst
C# 的返回類型分別映射到 C++ 結構和返回類型
請參考這個答案Marshaling C++ struct to C#
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.