将C++库嵌入.Net库中

Gra*_*ton 6 c# c++ pinvoke

在我的.Net程序集中,我必须使用一些本机(C++)dll.通常我们需要将C++ dll复制到bin文件夹中并用PInvoke它来调用它.为了节省分发成本,我想直接将C++嵌入到我的.Net dll中,这样分发的程序集数量就会减少.

知道怎么做吗?

Gre*_*osz 4

您可以将本机 DLL 作为资源嵌入。

然后在运行时,您必须将这些本机 DLL 提取到临时文件夹中;当您的应用程序启动时,您不一定具有对应用程序文件夹的写入权限:想想 Windows Vista 或 Windows 7 和 UAC。因此,您将使用此类代码从特定路径加载它们:

public static class NativeMethods {

  [DllImport("kernel32")]
  private unsafe static extern void* LoadLibrary(string dllname);

  [DllImport("kernel32")]
  private unsafe static extern void FreeLibrary(void* handle);

  private sealed unsafe class LibraryUnloader
  {
    internal LibraryUnloader(void* handle)
    {
      this.handle = handle;
    }

    ~LibraryUnloader()
    {
      if (handle != null)
        FreeLibrary(handle);
    }

    private void* handle;

  } // LibraryUnloader


  private static readonly LibraryUnloader unloader;

  static NativeMethods()
  {
    string path;

    // set the path according to some logic
    path = "somewhere/in/a/temporary/directory/Foo.dll";    

    unsafe
    {
      void* handle = LoadLibrary(path);

      if (handle == null)
        throw new DllNotFoundException("unable to find the native Foo library: " + path);

      unloader = new LibraryUnloader(handle);
    }
  }
}
Run Code Online (Sandbox Code Playgroud)