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

Car*_*sco 6 c# c++ iteration dll struct

我正在开发应该从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;
Run Code Online (Sandbox Code Playgroud)

}

这是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);
}
Run Code Online (Sandbox Code Playgroud)

所有类型都是C#中的String,并且它被假设保持这样,因此我唯一知道将要传递的结构.

任何的想法?

提前致谢

Dut*_*tts 2

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

来自 MSDN(此处)

.NET Framework ByValTStr 类型的行为类似于结构内的 C 风格固定大小字符串(例如 char s[5])

如果您使用 LPStr 或 LPWStr 空终止符,您将能够计算出它们的长度。