Delphi中DLL的结果,其中参数为PAnsiChar



我遇到了一个小问题。在我的DLL中,我有:

uses
ShareMem,
SysUtils,
Classes,
Dialogs;
function My_func (Param1, Param2, Param3: PAnsiChar) : Integer;
var
s1,s2,s3 : string;
begin
s1 := string(Param1);
s2 := string(Param2);
s3 := string(Param3);
ShowMessage(s1);
ShowMessage(s2);
ShowMessage(s3);
My_func := 0;
end;

还有我的TestUnit.pas 打来的电话

unit Utestunit;
interface
uses
ShareMem, Windows, Messages, SysUtils, Variants, Classes, Graphics, Controls, Forms,  Dialogs;
procedure Button1Click(Sender: TObject);
type
TMy_func = function (Param1, Param2, Param3: PAnsiChar) : Integer; StdCall;
var
my_func : TMyfunc;
error_code:integer;
My_library : THandle;
the_end : Boolean;
path_library,
path_library_full : string;
test1,
test2,
test3 : array [0..255] of AnsiChar;
begin
// open the DLL
path_library := ExtractFilePath(Application.ExeName)+'DLLRS_DLL.dll';
path_library_full := ExtractFilePath(Application.ExeName)+'DLL';
SetCurrentDir(path_library_full);
try
the_end := False;
My_library := SafeLoadLibrary(PChar(path_library));
if My_library > 32 then
begin
@My_func := GetProcAddress(My_library, PChar('My_func'));
if @My_func = nil then
begin
ShowMessage('There is no library in '+path_library);
the_end := True;
end;
end
else
begin
error_code := GetLastError;
ShowMessage('Błąd biblioteki '+ sciezka_biblioteki+' nr:'+IntToStr(error_code));
the_end := True;
end;
if not the_end then
begin
// the calling
test1 := 'My string nr 1';
test2 := 'My string nr 2';
test3 := 'My string nr 3';
kod_bledu := My_func(
test1,
test2,
test3
);      
end;
finally
FreeLibrary(My_library);
SetCurrentDir(ExtractFilePath(Application.ExeName))
end;
end;

结果是:

My string nr 1
trash
trash

作为来自我的DLL的消息。

为什么只有第一个结果是好的,而其他的都是垃圾?这只是我应用程序中的测试。

这段代码中有很多非常坏的习惯,我不想养成,因为这需要付出很多努力。

但是,出现这种行为的原因是您没有将DLL中的函数声明为stdcall。修复此问题,文本将正确传递。

最新更新