我需要从托管的 c++ 代码动态加载 .dll。下面的代码做到了这一点
[DllImport("kernel32.dll", SetLastError = true,
CharSet = CharSet::Unicode, ExactSpelling = true,
CallingConvention = CallingConvention::StdCall)]
static HMODULE LoadLibrary(LPCTSTR lpFileName);
[DllImport("kernel32.dll", SetLastError = true,
CharSet = CharSet::Unicode, ExactSpelling = true,
CallingConvention = CallingConvention::StdCall)]
static BOOL FreeLibrary(HMODULE hModule);
[DllImport("kernel32.dll", SetLastError = true,
CharSet = CharSet::Unicode, ExactSpelling = true,
CallingConvention = CallingConvention::StdCall)]
static FARPROC GetProcAddress(HMODULE hModule, LPCSTR lpProcName);
typedef int (*CFunction)();
int _tmain()
{
HMODULE pLib = LoadLibrary(TEXT("FunctionDLL.dll"));
if(pLib != 0)
{
FARPROC function = GetProcAddress(pLib, "QFunction");
if (function != 0)
MessageBox::Show(Convert::ToString(function()));
FreeLibrary(pLib);
}
else
{
MessageBox::Show(L"Error", L"Couldn't load ell");
Close();
}
return 0;
}
但函数始终为空。我认为 dll 我们错了。下面是dll的代码:
.h 文件
#ifdef __FUNCTIONDLL__
#define __FUNCTIONDLL__
#ifdef FUNCTIONDLL_EXPORTS
#define FUNCTIONDLL_API __declspec(dllexport)
#else
#define FUNCTIONDLL_API __declspec(dllimport)
#endif
#ifdef __cplusplus
extern "C"
{
#endif
FUNCTIONDLL_API int QFunction();
#ifdef __cplusplus
}
#endif // __cplusplus
#endif // __FUNCTIONDLL__
.cpp 文件
#include "FunctionDLL.h"
int QFunction()
{
return 42;
}