【发布时间】:2015-06-22 08:41:04
【问题描述】:
我在 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++ 站点上,我得到:“读取字符串字符时出错”
有人能解释一下吗?怎么了?在 c# 或 c++ 网站上?
【问题讨论】:
-
将
iu的MarshalAs更改为:[MarshalAs(UnmanagedType.LPStr)]。请注意,这仅适用于C#->C++。如果要将字符串从 C++ 传递到 C#,则需要做其他解决方案。 -
它就像一个魅力。不知道为什么它曾经工作......无论如何谢谢!
标签: c# c++ marshalling