Thema: Delphi How to - string in DLL

Einzelnen Beitrag anzeigen

WojTec

Registriert seit: 17. Mai 2007
482 Beiträge
 
Delphi XE6 Professional
 
#9

Re: How to - string in DLL

  Alt 19. Jun 2011, 20:14
Code (function from @Luckie article).

Delphi-Quellcode:
library StringDLL;

uses
  SysUtils;

function func1(s: PWideChar; Buffer: PWideChar; lenBuffer: Integer): Integer; stdcall;
var
  foo: String;
begin
  foo := 'foo'+ s;
  if Assigned(Buffer) then
    StrLCopy(Buffer, PWideChar(foo), lenBuffer);
  Result := Length(foo);
end;

exports
  func1;

begin
end.

function func1(s: PWideChar; Buffer: PWideChar; lenBuffer: Integer): Integer; external 'StringDLL.dll';

procedure TForm1.Button1Click(Sender: TObject);
var
  Buffer: array [0..MAX_PATH] of Char;
  BufferSize: DWORD;
begin
  BufferSize := High(Buffer);
  func1('bar', Buffer, BufferSize);
  ShowMessage(Buffer);
end;
Windows functions I'm using in the sam way, exception in DLL.

Original example is working:

Delphi-Quellcode:
procedure TForm1.FormCreate(Sender: TObject);
var
  hLib: THandle;
  s: String;
  foo1: function(s: PChar; Buffer: PChar; lenBuffer: Integer): Integer; stdcall;
  len: Integer;
  Buffer: PChar;
begin
  Buffer := nil;
  hLib := LoadLibrary('StringDLL.dll');
  if hLib = 0 then
  begin
    Str(GetLastError, s);
    ListBox1.Items.Add('LE: ' + s);
    exit;
  end;
  Str(hLib, s);
  ListBox1.Items.Add('hlib: ' + s);
  @foo1 := GetProcAddress(hLib, 'func1');
  if (not Assigned(foo1)) then
  begin
    Str(GetLastError, s);
    ListBox1.Items.Add('AE: ' + s);
    exit;
  end;
  Str(Integer(@foo1), s);
  ListBox1.Items.Add('@func1: ' + s);
  len := foo1('', nil, 0);
  Str(len, s);
  ListBox1.Items.Add('len: ' + s);
  try
    GetMem(Buffer, len + 1);
    len := foo1('', Buffer, len + 1);
    Str(len, s);
    ListBox1.Items.Add(String(Buffer)+ ' [' + s + ']');
  finally
    FreeMem(Buffer);
  end;
end;
I prefer 1st method (as in WinAPI). Why it don't working?

Geändert von WojTec (19. Jun 2011 um 20:18 Uhr) Grund: PWideChar
  Mit Zitat antworten Zitat