問題:
如何將非託管C DLL 嵌入到C DLL託管中C# DLL 使用DLLImport?
答案:
雖然通常不建議將非託管DLL 嵌入到託管DLL 中,但可以透過在初始化期間將非託管DLL 提取到臨時目錄來實現使用前使用LoadLibrary 明確載入它P/Invoke。
實作:
範例程式碼:
// Get temporary directory with assembly version in path string dirName = Path.Combine(Path.GetTempPath(), "MyAssembly." + Assembly.GetExecutingAssembly().GetName().Version); Directory.CreateDirectory(dirName); string dllPath = Path.Combine(dirName, "MyAssembly.Unmanaged.dll"); // Get embedded resource stream and copy DLL to temporary file using (Stream stm = Assembly.GetExecutingAssembly().GetManifestResourceStream("MyAssembly.Properties.MyAssembly.Unmanaged.dll")) { using (Stream outFile = File.Create(dllPath)) { const int sz = 4096; byte[] buf = new byte[sz]; while (true) { int nRead = stm.Read(buf, 0, sz); if (nRead < 1) break; outFile.Write(buf, 0, nRead); } } } // Load DLL explicitly IntPtr h = LoadLibrary(dllPath); Debug.Assert(h != IntPtr.Zero, "Unable to load library " + dllPath);
請注意,這種方法有其優點,例如將所有內容都保存在單一檔案中,但通常建議將非託管DLL 作為單獨的檔案連結到組件既安全又簡單。
以上是如何在託管 C# DLL 中嵌入非託管 DLL?的詳細內容。更多資訊請關注PHP中文網其他相關文章!