我试图用C++创建一个DLL并导出一个函数.
这是我的C++代码:
#include <Windows.h>
void DLLMain(){
}
__declspec(dllexport) void xMain(){
MessageBox(NULL,L"Test",L"Test",NULL);
}
Run Code Online (Sandbox Code Playgroud)
这是我的delphi代码:
program prjTestDllMain;
Uses
Windows;
Var
xMainPrc:procedure;stdcall;
handle : THandle;
begin
handle := LoadLibrary('xdll.dll');
if handle <> 0 then
begin
MessageBox(0,'DLL Loaded', 0, 0);
@xMainPrc := GetProcAddress(handle, 'xMain');
if @xMainPrc <> nil then
MessageBox(0,'Function Loaded', 0, 0)
else
MessageBox(0,'Function Not Loaded', 0, 0);
MessageBox(0,'Process End', 0, 0);
FreeLibrary(handle);
end else
MessageBox(0,'DLL Not Loaded', 0, 0);
end.
Run Code Online (Sandbox Code Playgroud)
我得到一个"DLL Loaded"的消息框就好了.但之后我得到"功能未加载".我在这做错了什么?
您可以将其导出为C函数(__cdecl),以便在exports表上有一个很好的名称.
名称 - 装饰约定:除了导出使用C链接的__cdecl函数时,下划线字符(_)以名称为前缀.
基本上,您的函数将xMain在exports表中具有名称.
extern "C" __declspec(dllexport) void xMain()
Run Code Online (Sandbox Code Playgroud)
在Delphi部分中,您只需指定cdecl并正常调用它:
var
xMainPrc: procedure; cdecl;
Run Code Online (Sandbox Code Playgroud)
例如:
if @xMainPrc <> nil then
begin
MessageBox(0,'Function Loaded', 0, 0);
xMainPrc;
end;
Run Code Online (Sandbox Code Playgroud)