Внедрение неуправляемой dll в управляемую С# dll
У меня есть управляемая С# dll, которая использует неуправляемую dll С++, используя DLLImport. Все отлично работает.
Тем не менее, я хочу встроить эту неуправляемую 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
"Неуправляемый драйвер .dll" - неуправляемая DLL
Когда я забегаю, я получаю:
Доступ запрещен. (Исключение из HRESULT: 0x80070005 (E_ACCESSDENIED))
Я видел из MSDN и http://blogs.msdn.com/suzcook/, которые должны быть возможны...
Ответы
Ответ 1
Вы можете встроить неуправляемую DLL в качестве ресурса, если вы извлечете ее во временную директорию во время инициализации и загрузите ее с помощью LoadLibrary с помощью P/Invoke. Я использовал эту технику, и она работает хорошо. Вы можете просто привязать его к сборке в виде отдельного файла, как отметил Майкл, но наличие всего в одном файле имеет свои преимущества. Здесь подход, который я использовал:
// Get a temporary directory in which we can store the unmanaged DLL, with
// this assembly 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 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
Вот мое решение, которое является измененной версией ответа 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
{
/// <summary>
/// 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
/// <list type="">
/// <item>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.</item>
/// <item>In a static constructor of your application, call EmbeddedDllClass.ExtractEmbeddedDlls() for each DLL that is needed</item>
/// <example>
/// EmbeddedDllClass.ExtractEmbeddedDlls("libFrontPanel-pinv.dll", Properties.Resources.libFrontPanel_pinv);
/// </example>
/// <item>Optional: In a static constructor of your application, call EmbeddedDllClass.LoadDll() to load the DLLs you have extracted. This is not necessary for pinvoke</item>
/// <example>
/// EmbeddedDllClass.LoadDll("myscrewball.dll");
/// </example>
/// <item>Continue using standard Pinvoke methods for the desired functions in the DLL</item>
/// </list>
/// </summary>
public class EmbeddedDllClass
{
private static string tempFolder = "";
/// <summary>
/// Extract DLLs from resources to temporary folder
/// </summary>
/// <param name="dllName">name of DLL file to create (including dll suffix)</param>
/// <param name="resourceBytes">The resource name (fully qualified)</param>
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);
/// <summary>
/// managed wrapper around LoadLibrary
/// </summary>
/// <param name="dllName"></param>
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);
}
}
}
}
Ответ 3
Я не знал, что это возможно - я бы предположил, что CLR нужно где-то извлечь встроенную локальную DLL (Windows должна иметь файл для загрузки DLL - он не может загружать изображение из необработанной памяти), и везде, где он пытается сделать это, у процесса нет разрешения.
Что-то вроде Process Monitor от SysInternals может дать вам ключ, если прорыв заключается в том, что создание файла DLL не выполняется...
Update:
А... теперь, когда я смог прочитать статью Suzanne Cook (страница для меня раньше не приходила), обратите внимание, что она не говорит о встраивании родной DLL в качестве ресурса внутри управляемой DLL, а скорее как связанный ресурс - родная DLL по-прежнему должна быть его собственным файлом в файловой системе.
Смотрите http://msdn.microsoft.com/en-us/library/xawyf94k.aspx, где говорится:
Файл ресурсов не добавляется в выходной файл. Это отличается от опции /resource, которая вставляет файл ресурсов в выходной файл.
Кажется, что это похоже на добавление метаданных в сборку, которая приводит к тому, что родная DLL логически является частью сборки (хотя это физически отдельный файл). Таким образом, такие вещи, как перенос управляемой сборки в GAC, автоматически включают в себя родную DLL и т.д.
Ответ 4
Вы можете попробовать Costura.Fody. Документация говорит, что она способна обрабатывать неуправляемые файлы. Я использовал его только для управляемых файлов, и он работает как шарм:)
Ответ 5
Можно также скопировать библиотеки DLL в любую папку, а затем вызвать SetDllDirectory в эту папку. В этом случае не требуется обращение к LoadLibrary.
[DllImport("kernel32.dll", CharSet = CharSet.Unicode, SetLastError = true)]
[return: MarshalAs(UnmanagedType.Bool)]
static extern bool SetDllDirectory(string lpPathName);