C# マネージ コードでアンマネージ コードを使用しています。アプリケーションの実行可能ファイルにアンマネージ DLL が埋め込まれています。これを機能させるために、DLL メソッドを呼び出す前に、リソース/DLL をファイルに抽出します。
public static class ResourceExtractor
{
public static void ExtractResourceToFile(string resourceName, string filename)
{
if (!System.IO.File.Exists(filename))
using (System.IO.Stream s = System.Reflection.Assembly.GetExecutingAssembly().GetManifestResourceStream(resourceName))
using (System.IO.FileStream fs = new System.IO.FileStream(filename, System.IO.FileMode.Create))
{
byte[] b = new byte[s.Length];
s.Read(b, 0, b.Length);
fs.Write(b, 0, b.Length);
}
}
}
そのため、DLL を呼び出す前に、次のことを確認します。
ResourceExtractor.ExtractResourceToFile("Namespace.dll_name.dll", "dll_name.dll");
そして、私が持っているアンマネージ DLL のメソッドをラップするには...
public class DLLWrapper
{
public const string dllPath = "dll_name.dll";
[DllImport(dllPath)]
public static extern uint functionA();
[DllImport(dllPath)]
public static extern uint functionB();
[DllImport(dllPath)]
public static extern uint functionC();
}
さて、質問ですが…
これはすべて機能します。私が気に入らないのは、実行可能ファイルの隣にある DLL を作成することです。一時ディレクトリに DLL を作成し、そこからロードしたいと思います。何かのようなもの...
string tempDLLname = Path.GetTempFileName();
ResourceExtractor.ExtractResourceToFile("Namespace.dll_name.dll", tempDLLname );
DLLWrapper.dllPath = tempDLLname;
...
public class DLLWrapper
{
public static string dllPath;
[DllImport(dllPath)]
public static extern uint functionA();
[DllImport(dllPath)]
public static extern uint functionB();
[DllImport(dllPath)]
public static extern uint functionC();
}
[DllImport(path)]
ただし、パスが である必要があるため、これは機能しませんconst
。では、DLL をロードする場所を変更するにはどうすればよいでしょうか。実行時までわかりません。