在C和C#之间传递包含结构数组的结构(DLL和P调用)
本文关键字:结构 DLL 调用 数组 包含 之间 | 更新日期: 2023-09-27 18:25:31
我有一个带有一些复杂结构的.dll,我真的是C#的新手:
typedef struct {
int a;
int b;
} simple_struct;
typedef struct {
int d;
int e;
simple_struct f[20];
short g;
simple_struct h[20];
short i;
} complex_struct;
问题是我无法将我的C#应用程序与此结构进行接口!!
DLL中有一个函数GetData(complex_struct*myStruct),我应该从C#调用它,所以我创建了:
[StructLayout(LayoutKind.Sequential, Pack = 1)]
unsafe struct simple_struct {
public int a;
public int b;
} ;
[StructLayout(LayoutKind.Sequential, Pack = 1)]
unsafe struct complex_struct {
public int d;
public int e;
public simple_struct[] f;
public short g;
public simple_struct[] h;
public short i;
} ;
但问题是,当我将complex_struct作为GetData的参数传递时,所有字段都会从我返回,而不是我的simple_struct的两个数组(我指的是f和h)!!它们的值为null!!
有人能帮我吗,谢谢
<小时>你好,谢谢你的回复,
我已经按照你说的做了,但当我调用GetData时,我仍然有另一个问题,进程在没有任何消息的情况下崩溃(一种异常):
这是我的C锐代码:命名空间dll_test_import_c_sharp{班级计划{[结构布局(LayoutKind.Sequential,Pack=1)]structsimple_struct{公共int a;公共int b;};
[StructLayout(LayoutKind.Sequential, Pack = 1)]
struct complex_struct {
public int d;
public int e;
[MarshalAs(UnmanagedType.ByValArray, SizeConst = 20)]
public simple_struct[] f;
public short g;
[MarshalAs(UnmanagedType.ByValArray, SizeConst = 20)]
public simple_struct[] h;
public short i;
} ;
[DllImport("test_dll.dll", CharSet = CharSet.Unicode)]
static extern int GetData(ref complex_struct a);
static void Main(string[] args)
{
complex_struct a = new complex_struct();
GetData(ref a);
return;
}
}
}
我做了很多printf I GetData,所有这些都执行得很好,看起来"return"指令崩溃了!!
我试图通过ref或out调用GetData,但两者都不起作用。。。
<小时>你好,谢谢你的回复,
我已经按照你说的做了,但当我调用GetData时,我仍然有另一个问题,进程在没有任何消息的情况下崩溃(一种异常):
这是我的C锐代码:命名空间dll_test_import_c_sharp{班级计划{[结构布局(LayoutKind.Sequential,Pack=1)]structsimple_struct{公共int a;公共int b;};
[StructLayout(LayoutKind.Sequential, Pack = 1)]
struct complex_struct {
public int d;
public int e;
[MarshalAs(UnmanagedType.ByValArray, SizeConst = 20)]
public simple_struct[] f;
public short g;
[MarshalAs(UnmanagedType.ByValArray, SizeConst = 20)]
public simple_struct[] h;
public short i;
} ;
[DllImport("test_dll.dll", CharSet = CharSet.Unicode)]
static extern int GetData(ref complex_struct a);
static void Main(string[] args)
{
complex_struct a = new complex_struct();
GetData(ref a);
return;
}
}
}
我做了很多printf I GetData,所有这些都执行得很好,看起来"return"指令崩溃了!!
我试图通过ref或out调用GetData,但两者都不起作用。。。
小时>小时>您需要更改struct
上的数组定义,以指定它是按值/内联数组
[StructLayout(LayoutKind.Sequential, Pack = 1)]
unsafe struct complex_struct {
public int d;
public int e;
[MarshalAs(UnmanagedType.ByValArray, SizeConst = 20)]
public simple_struct[] f;
public short g;
[MarshalAs(UnmanagedType.ByValArray, SizeConst = 20)]
public simple_struct[] h;
public short i;
} ;