实现 C++ 接口(interface)的 C# COM 程序集

标签 c# c++ com interop

有谁知道以下 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/

相关文章:

c# - 包含反斜杠的路径字符串无法识别的转义序列

c# - 在 ListView 中对项目进行分组 - Windows 应用商店应用

C++ Copy_if 使用 lambda

c++ - DirectX 11 将多个纹理加载到Texture2DArray中

c# - StaTaskScheduler和STA线程消息泵送

c# - 如何在 Kendo 调度程序资源(弹出窗口)中触发 DropDownList 事件

c# - Swagger 上传文件过滤器 5.0

android - 如何使用 msbuild 在命令行上覆盖项目属性

c++ - 如何使用 libev 在 C++ 中创建异步方法

c++ - 自定义结构化存储 IPropertySetStorage