[英]Embed C++ Libraries into .Net Libraries
在我的.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調用其中的方法。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.