C#COM组装实现C 接口

C# COM assembly implementing C++ interface

本文关键字:接口 实现 C#COM      更新时间:2023-10-16

是否有人知道C#中C 接口的以下实现是否正确,尤其是关于GUID类型的编组。

我们正在实施的原始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组装中的转换接口:

[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堆移动到不受管理的堆时,默认的填充类型为unmanagedtype.bstr.bstr(Unicode字符串,长度置换) - 在这种情况下,主机应用程序需要不同的元帅类型:

public string Name { [return: MarshalAs(UnmanagedType.HString)]get; }