我想从非托管C++中写入的32位和64位DLL导入一些函数到我的C#项目中。作为一个样本,我这样做:动态和静态导入非托管C++ 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();
}
}
}
我似乎无法得到它的工作。这里是我得到的错误消息:
- 当我使用DLLWrapper类与32位DLL文件我得到“DLLNotFoundException”,但DLL文件正是在该路径。
- 当我使用带有64位DLL文件的DLLWrapper类并将“Platform Target”属性更改为“x64”时,我得到相同的“DLLNotFoundException”,如果我尝试使用“x86”构建,那么会得到“BadImageException” 。
- 当我使用DynamicDLLImport类时,我总是在代码中的“HERE ARGUMENTNULLEXCEPTION”注释行中得到“ArgumentNullException”。
我在做什么错?
我也试过,还是一样的错误。 – hattenn 2012-07-17 08:38:49
你是否声明'mult'作为一个dll导出方法? – zmbq 2012-07-17 08:39:54
我确实从同事那里得到了DLL,但他知道他在做什么,所以我不指望它没有声明为dll导出方法。 – hattenn 2012-07-17 08:41:57