Sunday, March 22, 2009

Using PInvoke from Delphi for .NET

Recently I was asked how to call a DLL exporting methods that have a char* parameter from Delphi for .NET. It's really easy but getting all the details right can be a pain. So here is a really simple example so I can just say "go to my blog" when asked again :)

Say you have two methods in a DLL:


library StringLibrary;

uses SysUtils, Classes, Dialogs;

{$R *.res}

procedure PassInPChar(S: PChar); stdcall;
begin
ShowMessage(S);
end;

procedure ReturnPChar(S: PChar); stdcall;
begin
ShowMessage(S);
StrCopy(S, 'Hello Delphi');
end;

exports
PassInPChar, ReturnPChar;

begin
end.


Don't forget stdcall. On the Delphi for .NET side define the exported function prototypes as:


[DllImport('StringLibrary.dll')]
procedure PassInPChar(S: string); external;

[DllImport('StringLibrary.dll')]
procedure ReturnPChar(S: StringBuilder); external;


Notice that I used StringBuilder in the second method. This is because the callee is going to modify the string. Now to invoke the methods do something like the following:


procedure TForm3.Button1Click(Sender: TObject);
begin
PassInPChar(Edit1.Text);
end;

procedure TForm3.Button2Click(Sender: TObject);
var
S: StringBuilder;
begin
S := StringBuilder.Create(Edit2.Text, 256);
ReturnPChar(S);
Edit3.Text := S.ToString;
end;

No comments: