简体   繁体   中英

Implement C# interface in an unmanaged cpp dll

I have a C# apllication having add-ons capability. An add-on/plug-in that implements a specific interface can be linked/loaded at runtime to the main C# application.

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?

Thanks, Cabbi

You can implement interface using p/inkove, for example:

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.

And you can load unmanaged dll via PInvoke in .Net, but I'd rather not recommend that way.

Strictly speaking, you cannot have an unmanaged DLL that implements a C# (managed) interface.

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.

In addition, you can use PInvoke to consume a pure native DLL from a NET assembly.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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