从 C# 到 C++ 的结构中编组结构

Marshal struct in struct from c# to c++

我在 C# 和 C++ 中有以下结构。

C++:

struct TestA
{
    char* iu;       
};

struct TestB
{   
    int cycle1;
    int cycle2; 
};

struct MainStruct
{   
    TestA test;
    TestB test2;
};

C#:

[StructLayout(LayoutKind.Sequential, CharSet=CharSet.Ansi, Pack = 1)]
internal struct TestA
{
    [MarshalAs(UnmanagedType.ByValTStr, SizeConst = 36)]
    private string iu;

    public TestA(Guid Iu)
        : this()
    {
        iu = Iu.ToString("D");
    }
}

[StructLayout(LayoutKind.Sequential), Serializable]
internal struct TestB
{
    int cycle1;
    int cycle2; 
}

[StructLayout(LayoutKind.Sequential)]
internal struct MainStruct
{        
    private TestA testA;    
    private TestB testB;

    private MainStruct(TestA Test_A) : this()
    {
       testA = Test_A;
    }

    public static MainStruct Initial(TestA Test_A, TestB Test_B)
    {
        return new MainStruct(Test_A)
        {
            testB = Test_B
        };
    }            
}

编组数据一直有效,直到我不得不编写结合了其他两个的结构 (MainStruct)。 C++ 不接收数据。在 C++ 站点上,我得到:"Error reading characters of string"

有人能解释一下吗?怎么了?在 c# 或 c++ 站点上?

改变这个:

[MarshalAs(UnmanagedType.ByValTStr, SizeConst = 36)]
private string iu;

对此:

[MarshalAs(UnmanagedType.LPStr)]
private string iu;

请注意,此代码仅适用于在 C#->C++ 方向上传递字符串。对于相反的方向(C++->C#),它更复杂,因为 C# 不能轻易地释放 C++ 分配的内存。

其他重要事项:如果将此结构传递给 C++ 方法,例如:

TestA a = new TestA(Guid.NewGuid());
SomeCPlusPlusMethod(a);

指针 char* iu 的生命周期将在 SomeCPlusPlusMethod 方法调用结束时结束...C# 封送拆收器将在调用 SomeCPlusPlusMethod 之前分配一些内存并将释放该内存调用后的内存 SomeCPlusPlusMethod。如果 C++ 方法想要保存 char* iu,这很重要。在那种情况下,它必须 strdup(iu) 或类似的东西。