【问题标题】:Implement C# interface in an unmanaged cpp dll在非托管 cpp dll 中实现 C# 接口
【发布时间】:2013-06-01 06:34:35
【问题描述】:

我有一个具有附加功能的 C# 应用程序。实现特定接口的插件/插件可以在运行时链接/加载到主 C# 应用程序。

现在我的问题是:如何开发实现 C# 接口并将运行时加载到 C# 应用程序的非托管 cpp dll?

谢谢, 出租车

【问题讨论】:

    标签: c# c++ plugins interface add-on


    【解决方案1】:

    可以使用p/inkove实现接口,例如:

    public interface IDirectory
    {
        bool IsDirectoryEmplty(string path);
    }
    
    public class Directory : IDirectory
    {
        [DllImport("Shlwapi.dll", EntryPoint = "PathIsDirectoryEmpty")]
        [return: MarshalAs(UnmanagedType.Bool)]
        public static extern bool IsDirectoryEmplty([MarshalAs(UnmanagedType.LPStr)]string directory);
    
        bool IInterface.IsDirectoryEmplty(string path)
        {
            return IsDirectoryEmplty(path);
        }
    }
    

    【讨论】:

    • 与仅调用 C# 方法相比,您对性能有什么概念吗?开销大吗?
    • 我认为,这样的实现(外部c/c++)只能用于大型计算
    【解决方案2】:

    启用common language support,您可以编写包含完整本机 c++ 功能的托管 dll。

    您可以在 .Net 中通过 PInvoke 加载非托管 dll,但我不推荐这种方式。

    【讨论】:

    • 为什么不推荐“PInvoke”?
    • @Cabbi C++/CLI 比 PInvoke 更容易编写。即使在大部分时间里,C++/CLI 也比 PInvoke 快。
    【解决方案3】:

    严格来说,您不能拥有实现 C#(托管)接口的 非托管 DLL。

    但是,您可以创建一个mixed mode assembly,这可能就是您想要的。这是提供带有 .NET 包装器的本机 C++(非托管)实现的一种非常常见的方式,使其成为看起来受 C#(或其他 .NET 语言)使用者管理的程序集。

    此外,您可以使用PInvoke 来使用来自 NET 程序集的纯本机 DLL。

    【讨论】:

    • ...我不知道混合模式,太好了!
    • 我将调查“PInvoke”开销。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2011-04-29
    • 1970-01-01
    • 2010-10-14
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多