当前位置:  开发笔记 > 编程语言 > 正文

将非托管dll嵌入到托管C#dll中

如何解决《将非托管dll嵌入到托管C#dll中》经验,为你挑选了4个好方法。

我有一个使用DLLImport使用非托管C++ DLL的托管C#dll.一切都很好.但是,我想在我的托管DLL中嵌入非托管DLL,如Microsoft解释:

http://msdn.microsoft.com/en-us/library/system.runtime.interopservices.dllimportattribute.dllimportattribute.aspx

所以我将非托管dll文件添加到我的托管dll项目,将属性设置为'Embedded Resource'并将DLLImport修改为:

[DllImport("Unmanaged Driver.dll, Wrapper Engine, Version=1.0.0.0,
Culture=neutral, PublicKeyToken=null",
CallingConvention = CallingConvention.Winapi)]

其中'Wrapper Engine'是我托管DLL的程序集名称'Unmanaged Driver.dll'是非托管DLL

当我跑步时,我得到:

访问被拒绝.(HRESULT异常:0x80070005(E_ACCESSDENIED))

我从MSDN和http://blogs.msdn.com/suzcook/看到了这应该是可能的......



1> JayMcClellan..:

如果在初始化期间将其自身提取到临时目录,则可以将非托管DLL作为资源嵌入,并在使用P/Invoke之前使用LoadLibrary显式加载它.我使用过这种技术,效果很好.您可能更喜欢将它作为单独的文件链接到程序集,正如Michael所指出的那样,但将它全部放在一个文件中有其优点.这是我使用的方法:

// Get a temporary directory in which we can store the unmanaged DLL, with
// this assembly's version number in the path in order to avoid version
// conflicts in case two applications are running at once with different versions
string dirName = Path.Combine(Path.GetTempPath(), "MyAssembly." +
  Assembly.GetExecutingAssembly().GetName().Version.ToString());
if (!Directory.Exists(dirName))
  Directory.CreateDirectory(dirName);
string dllPath = Path.Combine(dirName, "MyAssembly.Unmanaged.dll");

// Get the embedded resource stream that holds the Internal DLL in this assembly.
// The name looks funny because it must be the default namespace of this project
// (MyAssembly.) plus the name of the Properties subdirectory where the
// embedded resource resides (Properties.) plus the name of the file.
using (Stream stm = Assembly.GetExecutingAssembly().GetManifestResourceStream(
  "MyAssembly.Properties.MyAssembly.Unmanaged.dll"))
{
  // Copy the assembly to the temporary file
  try
  {
    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);
      }
    }
  }
  catch
  {
    // This may happen if another process has already created and loaded the file.
    // Since the directory includes the version number of this assembly we can
    // assume that it's the same bits, so we just ignore the excecption here and
    // load the DLL.
  }
}

// We must explicitly load the DLL here because the temporary directory 
// is not in the PATH.
// Once it is loaded, the DllImport directives that use the DLL will use
// the one that is already loaded into the process.
IntPtr h = LoadLibrary(dllPath);
Debug.Assert(h != IntPtr.Zero, "Unable to load library " + dllPath);



2> Mark Lakata..:

这是我的解决方案,这是JayMcClellan的答案的修改版本.将下面的文件保存到class.cs文件中.

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Runtime.InteropServices;
using System.IO;
using System.Reflection;
using System.Diagnostics;
using System.ComponentModel;

namespace Qromodyn
{
    /// 
    /// A class used by managed classes to managed unmanaged DLLs.
    /// This will extract and load DLLs from embedded binary resources.
    /// 
    /// This can be used with pinvoke, as well as manually loading DLLs your own way. If you use pinvoke, you don't need to load the DLLs, just
    /// extract them. When the DLLs are extracted, the %PATH% environment variable is updated to point to the temporary folder.
    ///
    /// To Use
    /// 
    /// Add all of the DLLs as binary file resources to the project Propeties. Double click Properties/Resources.resx,
    /// Add Resource, Add Existing File. The resource name will be similar but not exactly the same as the DLL file name.
    /// In a static constructor of your application, call EmbeddedDllClass.ExtractEmbeddedDlls() for each DLL that is needed
    /// 
    ///               EmbeddedDllClass.ExtractEmbeddedDlls("libFrontPanel-pinv.dll", Properties.Resources.libFrontPanel_pinv);
    /// 
    /// Optional: In a static constructor of your application, call EmbeddedDllClass.LoadDll() to load the DLLs you have extracted. This is not necessary for pinvoke
    /// 
    ///               EmbeddedDllClass.LoadDll("myscrewball.dll");
    /// 
    /// Continue using standard Pinvoke methods for the desired functions in the DLL
    /// 
    /// 
    public class EmbeddedDllClass
    {
        private static string tempFolder = "";

        /// 
        /// Extract DLLs from resources to temporary folder
        /// 
        /// name of DLL file to create (including dll suffix)
        /// The resource name (fully qualified)
        public static void ExtractEmbeddedDlls(string dllName, byte[] resourceBytes)
        {
            Assembly assem = Assembly.GetExecutingAssembly();
            string[] names = assem.GetManifestResourceNames();
            AssemblyName an = assem.GetName();

            // The temporary folder holds one or more of the temporary DLLs
            // It is made "unique" to avoid different versions of the DLL or architectures.
            tempFolder = String.Format("{0}.{1}.{2}", an.Name, an.ProcessorArchitecture, an.Version);

            string dirName = Path.Combine(Path.GetTempPath(), tempFolder);
            if (!Directory.Exists(dirName))
            {
                Directory.CreateDirectory(dirName);
            }

            // Add the temporary dirName to the PATH environment variable (at the head!)
            string path = Environment.GetEnvironmentVariable("PATH");
            string[] pathPieces = path.Split(';');
            bool found = false;
            foreach (string pathPiece in pathPieces)
            {
                if (pathPiece == dirName)
                {
                    found = true;
                    break;
                }
            }
            if (!found)
            {
                Environment.SetEnvironmentVariable("PATH", dirName + ";" + path);
            }

            // See if the file exists, avoid rewriting it if not necessary
            string dllPath = Path.Combine(dirName, dllName);
            bool rewrite = true;
            if (File.Exists(dllPath)) {
                byte[] existing = File.ReadAllBytes(dllPath);
                if (resourceBytes.SequenceEqual(existing))
                {
                    rewrite = false;
                }
            }
            if (rewrite)
            {
                File.WriteAllBytes(dllPath, resourceBytes);
            }
        }

        [DllImport("kernel32", SetLastError = true, CharSet = CharSet.Unicode)]
        static extern IntPtr LoadLibrary(string lpFileName);

        /// 
        /// managed wrapper around LoadLibrary
        /// 
        /// 
        static public void LoadDll(string dllName)
        {
            if (tempFolder == "")
            {
                throw new Exception("Please call ExtractEmbeddedDlls before LoadDll");
            }
            IntPtr h = LoadLibrary(dllName);
            if (h == IntPtr.Zero)
            {
                Exception e = new Win32Exception();
                throw new DllNotFoundException("Unable to load library: " + dllName + " from " + tempFolder, e);
            }
        }

    }
}


马克,这真的很酷.对于我的用途,我发现我可以删除LoadDll()方法,并在ExtractEmbeddedDlls()的末尾调用LoadLibrary().这也允许我删除PATH修改代码.

3> Matthias..:

你可以试试Costura.Fody.文档说,它能够处理非托管文件.我只将它用于托管文件,它就像一个魅力:)



4> Michael Burr..:

我不知道这是可能的 - 我猜想CLR需要在某处提取嵌入式本机DLL(Windows需要有一个DLL加载文件的文件 - 它无法从原始内存加载图像),以及任何地方它试图这样做,该过程没有权限.

像SysInternals的Process Monitor这样的东西可能会给你一个线索,如果问题是创建DLL文件失败了......

更新:


啊......现在我已经能够阅读Suzanne Cook的文章了(之前没有找到我的页面),请注意她并没有谈论将本机DLL作为托管DLL中的资源嵌入,而是作为链接资源 - 本机DLL仍然需要是文件系统中自己的文件.

请参阅http://msdn.microsoft.com/en-us/library/xawyf94k.aspx,其中说:

资源文件未添加到输出文件中.这与将资源文件嵌入输出文件的/ resource选项不同.

这似乎做的是向程序集添加元数据,导致本机DLL在逻辑上成为程序集的一部分(即使它在物理上是一个单独的文件).因此,将托管程序集放入GAC会自动包含本机DLL等.

推荐阅读
手机用户2402852307
这个屌丝很懒,什么也没留下!
DevBox开发工具箱 | 专业的在线开发工具网站    京公网安备 11010802040832号  |  京ICP备19059560号-6
Copyright © 1998 - 2020 DevBox.CN. All Rights Reserved devBox.cn 开发工具箱 版权所有