简体   繁体   English

在非托管cpp dll中实现C#接口

[英]Implement C# interface in an unmanaged cpp dll

I have a C# apllication having add-ons capability. 我有一个具有附加功能的C#应用​​程序。 An add-on/plug-in that implements a specific interface can be linked/loaded at runtime to the main C# application. 可以在运行时将实现特定接口的加载项/插件链接/加载到主C#应用程序。

Now to my question: how can I develop an unmanaged cpp dll that implements the C# interface and be loaded runtime to the C# app? 现在我的问题是:如何开发实现C#接口的非托管cpp dll并在运行时将其加载到C#应用程序?

Thanks, Cabbi 谢谢,卡比

You can implement interface using p/inkove, for example: 您可以使用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);
    }
}

With common language support on, you can write managed dll with full native c++ capability mixed in. 启用common language support ,您可以编写具有完整本机c ++功能的托管dll。

And you can load unmanaged dll via PInvoke in .Net, but I'd rather not recommend that way. 而且您可以通过.Net中的PInvoke加载非托管dll,但我不建议这样做。

Strictly speaking, you cannot have an unmanaged DLL that implements a C# (managed) interface. 严格来说,您不能拥有实现C#(托管)接口的非托管 DLL。

However, you can create a mixed mode assembly , that might be what you want. 但是,您可以创建一个混合模式的程序集 ,这可能是您想要的。 This is a very common way to provide a native C++ (unmanaged) implementation with a .NET wrapper making it an assembly that looks managed to a C# (or other .NET language) consumer. 这是向本地C ++(非托管)实现提供.NET包装的一种非常常见的方法,使之成为对C#(或其他.NET语言)使用者而言看起来受管理的程序集。

In addition, you can use PInvoke to consume a pure native DLL from a NET assembly. 此外,您可以使用PInvoke从NET程序集中使用纯本机DLL。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM