Joined: 29 Nov 2006 Posts: 449 Location: The yogurt country
Posted: Mon Mar 16, 2009 1:27 pm Post subject: [Delphi] Exporting function (and using it)
I can't believe i have problems with such a silly thing. Who knows what i am missing ...
Anyway here is what i have:
DLL:
Code:
library my_lib;
uses
Windows;
function cool_func():string;
var
good:string;
begin
good:='this function is good';
result := good;
end;
exports
cool_func;
begin
end.
EXECUTABLE:
Code:
............
function cool_func:string;
external 'my_lib.dll' name 'cool_func';
var
Form1: TForm1;
implementation
{$R *.dfm}
procedure TForm1.Button1Click(Sender: TObject);
begin
showmessage(cool_func);
end;
end.
So far - so good!
I click button1 and get the string "this function is good" in a showmessage.
After i click [OK] in that "showmessage" i get the following error:
How can i fix that? What i am doing wrong?
(my function must be able to be called from another languages/applications too without errors) _________________
Joined: 04 May 2007 Posts: 955 Location: Why do you care?
Posted: Mon Mar 16, 2009 2:27 pm Post subject:
I recall something about exporting functions which return strings in Delphi DLLs, where you have to add Borland's string library to the first of your list of uses or something like that.
Read the comment that was created by the DLL project wizard.
Code:
{ Important note about DLL memory management: ShareMem must be the
first unit in your library's USES clause AND your project's (select
Project-View Source) USES clause if your DLL exports any procedures or
functions that pass strings as parameters or function results. This
applies to all strings passed to and from your DLL--even those that
are nested in records and classes. ShareMem is the interface unit to
the BORLNDMM.DLL shared memory manager, which must be deployed along
with your DLL. To avoid using BORLNDMM.DLL, pass string information
using PChar or ShortString parameters. }
This would be a workaround if you didn't want to use ShareMem would be:
Code:
library my_lib;
uses
Windows;
var
HoldingString: string;
function cool_func: PChar; stdcall;
begin
HoldingString := 'this function is good';
Result := PChar(HoldingString);
end;
exports
cool_func;
begin
end.
With that code you could then do this:
Code:
function cool_func: PChar; stdcall; external 'my_lib.dll' name 'cool_func';
implementation
{$R *.dfm}
procedure TForm1.Button1Click(Sender: TObject);
begin
ShowMessage(cool_func);
end;
You cannot post new topics in this forum You cannot reply to topics in this forum You cannot edit your posts in this forum You cannot delete your posts in this forum You cannot vote in polls in this forum You cannot attach files in this forum You can download files in this forum