[英]How to marshal a pointer to fixed size array in c#
我有一个带有导出函数的 C++ DLL:
__declspec (dllexport) int AllocateBuf(DataBufferIn *in);
该函数分配缓冲区数组并为测试赋值
__declspec (dllexport) int AllocateBuf(DataBufferIn *in){
for (int i = 0 ; i < 4; i++){
in->data_r[i] = (double*)VirtualAlloc(
NULL, // System selects address
1024 * sizeof(double), // Size of allocation
MEM_RESERVE | MEM_COMMIT, // Allocate reserved pages
PAGE_READWRITE); // Protection = no access
for (int j = 0; j < 128; i++){
(in->data_r[i])[j] = j;//Assign value for test
}
}
}
struct DataBufferIn 是这样的
struct DataBufferIn
{
double* data_r[4];
double* data_g[4];
};
以下是我的代码,我想在 c# 中编组这个结构,但我得到一个异常(An unhandled exception of type 'System.Runtime.InteropServices.SafeArrayTypeMismatchException' occurred in C_Sharp_Sample.exe)
。 我经常被卡在这个问题上,有人知道如何解决这个问题吗? 谢谢 :)
public struct DataBufferIn
{
[MarshalAs(UnmanagedType.ByValArray, SizeConst = 4)]
public IntPtr[] data_r;
[MarshalAs(UnmanagedType.ByValArray, SizeConst = 4)]
public IntPtr[] data_g;
};
[DllImport("test.dll", CallingConvention = CallingConvention.Cdecl)]
public static extern int AllocateBuf(ref DataBufferIn _data_buf_in);
private void button_allocate_buf_Click(object sender, EventArgs e)
{
DataBufferIn data_buf_in = new DataBufferIn();
AllocateBuf(ref data_buf_in);//<---Function call fail...
double[] doubleArrayRed = new double[1024];
Marshal.Copy(data_buf_in.lum_data_r[0], doubleArrayRed, 0, 1024);
.....
}
根据 Charlieface 的建议,添加 [StructLayout(LayoutKind.Sequential)] 可以解决这个问题。
[StructLayout(LayoutKind.Sequential)]
public struct DataBufferIn
{
[MarshalAs(UnmanagedType.ByValArray, SizeConst = 4)]
public IntPtr[] data_r;
[MarshalAs(UnmanagedType.ByValArray, SizeConst = 4)]
public IntPtr[] data_g;
};
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.