アンマネージC++で記述された32ビットおよび64ビットDLLからC#プロジェクトにいくつかの関数をインポートしようとしています。サンプルとして、私はこれを行いました:
C++DLL関数
long mult(int a, int b) {
return ((long) a)*((long) b);
}
C#コード
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Runtime.InteropServices;
namespace ConsoleApplication2
{
class DynamicDLLImport
{
private IntPtr ptrToDll;
private IntPtr ptrToFunctionToCall;
[DllImport("kernel32.dll")]
public static extern IntPtr LoadLibrary(string dllToLoad);
[DllImport("kernel32.dll")]
public static extern IntPtr GetProcAddress(IntPtr hModule, string procedureName);
[DllImport("kernel32.dll")]
public static extern bool FreeLibrary(IntPtr hModule);
[UnmanagedFunctionPointer(CallingConvention.Cdecl)]
private delegate int Multiply(int a, int b);
private Multiply multiply;
public DynamicDLLImport(string dllName)
{
ptrToDll = LoadLibrary(dllName);
// TODO: Error handling.
ptrToFunctionToCall = GetProcAddress(ptrToDll, "mult");
// TODO: Error handling.
// HERE ARGUMENTNULLEXCEPTION
multiply = (Multiply)Marshal.GetDelegateForFunctionPointer(ptrToFunctionToCall, typeof(Multiply));
}
public int mult_func(int a, int b)
{
return multiply(a, b);
}
~DynamicDLLImport()
{
FreeLibrary(ptrToDll);
}
}
class DLLWrapper
{
private const string Sixtyfour = "c:\\Users\\Hattenn\\Documents\\Visual Studio 2010\\Projects\\ConsoleApplication2\\ConsoleApplication2\\easyDLL0_64.dll";
private const string Thirtytwo = "c:\\Users\\Hattenn\\Documents\\Visual Studio 2010\\Projects\\ConsoleApplication2\\ConsoleApplication2\\easyDLL0.dll";
// [DllImport(Sixtyfour)]
// public static extern int mult(int a, int b);
[DllImport(Thirtytwo)]
public static extern int mult(int a, int b);
}
class Program
{
static void Main(string[] args)
{
int a = 5;
int b = 4;
DynamicDLLImport dllimp = new DynamicDLLImport("easyDLL0.dll");
Console.WriteLine(DLLWrapper.mult(a, b));
//Console.WriteLine(dllimp.mult_func(a, b));
Console.ReadKey();
}
}
}
私はそれを機能させることができないようです。表示されるエラーメッセージは次のとおりです。
- 32ビットDLLファイルでDLLWrapperクラスを使用すると、「DLLNotFoundException」が発生しますが、DLLファイルは正確にそのパスにあります。
- 64ビットDLLファイルでDLLWrapperクラスを使用し、「PlatformTarget」プロパティを「x64」に変更すると、同じ「DLLNotFoundException」が発生します。「x86」でビルドしようとすると、「BadImageException」が発生します。
- DynamicDLLImportクラスを使用すると、コード内で「HEREARGUMENTNULLEXCEPTION」とコメントされた行で常に「ArgumentNullException」が発生します。
私は何が間違っているのですか?