有谁知道以下 C# 中 C++ 接口(interface)的实现是否正确,特别是关于 GUID 类型的编码(marshal)处理。
我们正在实现的原始 C++:
[
object,
pointer_default(unique),
uuid(Z703B6E9-A050-4C3C-A050-6A5F4EE32767)
]
interface IThing: IUnknown
{
[propget] HRESULT Prop1([out, retval] GUID* prop1);
[propget] HRESULT Prop2([out, retval] EnumProp2* prop2);
[propget] HRESULT Prop3([out, retval] HSTRING* prop3);
};
我们的 C# COM 程序集中转换后的接口(interface):
[ComVisible(true), Guid("Z703B6E9-A050-4C3C-A050-6A5F4EE32767"), InterfaceType(ComInterfaceType.InterfaceIsIUnknown)]
public interface IThing
{
Guid Prop1 { get; }
EnumProp2 Prop2 { get; }
string Prop3 { get; }
}
具体类:
public class Thing : IThing
{
public Thing(Guid prop1, EnumProp2 prop2, string prop3)
{
Prop1 = prop1;
Prop2 = prop2;
Prop3 = prop3;
}
public Guid Prop1 { get; }
public EnumProp2 Prop2 { get; }
public string Prop3 { get; }
}
最佳答案
事实证明问题实际上不是编码 Guid
结构,而是 string
。
似乎将字符串从托管 CLR 堆移动到非托管堆时,默认的编码(marshal)处理类型是 UnmanagedType.BStr(unicode 字符串,长度前缀)- 在这种情况下,主机应用程序需要不同的编码(marshal)处理类型:
public string Name { [return: MarshalAs(UnmanagedType.HString)]get; }
关于实现 C++ 接口(interface)的 C# COM 程序集,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/42751402/