问题:
如何将非托管 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中文网其他相关文章!