gpt4 book ai didi

delphi - Delphi 中 DLL 的隐式链接与显式链接

转载 作者:行者123 更新时间:2023-12-03 18:05:04 27 4
gpt4 key购买 nike

在使用显式链接时,我无法让我的 dll 正常工作。使用隐式链接它工作正常。有人会用谷歌搜索我的解决方案吗? :) 不,开个玩笑,这是我的代码:

这段代码工作正常:

function CountChars(_s: Pchar): integer; StdCall; external 'sample_dll.dll';

procedure TForm1.Button1Click(Sender: TObject);
begin
ShowMessage(IntToStr(CountChars('Hello world')));
end;

此代码不起作用(我遇到访问冲突):

procedure TForm1.Button1Click(Sender: TObject);
var
LibHandle: HMODULE;
CountChars: function(_s: PChar): integer;
begin

LibHandle := LoadLibrary('sample_dll.dll');
ShowMessage(IntToStr(CountChars('Hello world'))); // Access violation
FreeLibrary(LibHandle);
end;

这是动态链接库代码:

library sample_dll;

uses
FastMM4, FastMM4Messages, SysUtils, Classes;

{$R *.res}

function CountChars(_s: PChar): integer; stdcall;
begin
Result := Length(_s);
end;

exports
CountChars;

begin
end.

最佳答案

procedure TForm1.Button1Click(Sender: TObject);
var
LibHandle: HMODULE;
CountChars: function(_s: PChar): integer; stdcall; // don't forget the calling convention
begin
LibHandle := LoadLibrary('sample_dll.dll');
if LibHandle = 0 then
RaiseLastOSError;
try
CountChars := GetProcAddress(LibHandle, 'CountChars'); // get the exported function address
if not Assigned(@CountChars) then
RaiseLastOSError;

ShowMessage(IntToStr(CountChars('Hello world')));
finally
FreeLibrary(LibHandle);
end;
end;

关于delphi - Delphi 中 DLL 的隐式链接与显式链接,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/2673639/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com