我正在尝试从非托管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();
}
}
}
我似乎无法正常工作。这是我收到的错误消息:
我究竟做错了什么?
最佳答案
您是如何从DLL中导出函数的? Windows DLL不会自动导出所有函数,并且C++会修饰名称,例如,以区分函数重载,除非您不告诉它,但确切地说是特定于编译器的,而其他语言肯定不理解。
您可以通过启动Visual Studio命令提示符并使用以下命令进行检查
dumpbin /EXPORTS "your library.dll"
关于c# - 动态地和静态地将非托管C++ DLL导入C#不起作用,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/11518577/