将C ++库嵌入.Net库中

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

知道怎么做吗?

您可以将本机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); } } } 

你可以将你的dll作为资源嵌入。

在运行时,将它们提取到与exe相同的文件夹中,并使用P / Invoke调用其中的方法。