我正在开发应该从 C# 程序访问的 ac .dll。理想情况下,.dll 应该接收在 C# 中定义的任何结构并对其进行处理。因此,最初,C dll 的结构类型和大小是未知的。我可以通过 C 的 extern 函数传递结构,并且应该可以接收它,但是,有没有办法找出这个接收结构的大小和特征?有没有办法迭代它的成员?
这是为 dll 定义的 C 函数
extern int __cdecl testCSharp(mystruct * Test){
//sizeof(Test) is 4, so it is ok
for(int i=0;i < sizeof(Test) ; i++){
char * value = (char*) Test; //This access the first element.
cout << value << endl; //Prints "some random string", so, it is received ok
}
return 1;
}
这是 C# 代码
[StructLayout(LayoutKind.Sequential,CharSet=CharSet.Ansi)]
unsafe public struct myStruct{
[MarshalAsAttribute(UnmanagedType.ByValTStr, SizeConst = 100)]
public string value1;
[MarshalAsAttribute(UnmanagedType.ByValTStr, SizeConst = 100)]
public string value2;
[MarshalAsAttribute(UnmanagedType.ByValTStr, SizeConst = 100)]
public string value3;
[MarshalAsAttribute(UnmanagedType.ByValTStr, SizeConst = 100)]
public string value4;
};
[DllImport("SMKcomUploadDLL.dll", CallingConvention = CallingConvention.Cdecl)]
public static extern int testCSharp(ref myStruct message);
static void Main()
{
int result;
myStruct message = new myStruct();
message.value1 = "Some randome string";
message.value2 = "0";
message.value3 = "olkujhikvb";
message.value4 = "isabedfbfmlk";
result = testCSharp(ref message);
}
所有类型在 C# 中都是 String,并且应该保持这种状态,所以我知道的关于将要传递的结构的唯一信息。
任何想法?
提前致谢