对从c#传递的未知c结构进行迭代

iterate over unknown c struct passed from c#

本文关键字:结构 迭代 未知 对从      更新时间:2023-10-16

我正在开发一个应该从c#程序访问的c.dll。理想情况下,.dll应该接收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,并且假设它保持原样,所以它是我对将要传递的结构唯一了解的内容。

知道吗?

提前感谢

当您将它们编组为长度为100的ByValTStr时,我不确定您是否能够处理比现有元素(即第一个元素)更多的内容。

来自MSDN(此处)

.NET Framework ByValTStr类型的行为类似于C样式、固定大小的字符串在结构内部(例如,char s[5])

如果使用LPStr或LPWStr null终止,则可以计算出它们的长度。