Forum > Packages and Libraries
[SOLVED] dll/library runtime error 216
(1/1)
Maciej Kaczkowski:
Hi,
I would like to create my first library, but after few test I have problem with TStringList class as data container inside function. Here is full app:
library part
--- Code: ---library libtest;
{$mode objfpc}{$H+}
uses
Classes;
var
f: TStringList;
function test: string;
begin
Result := f.Text;
end;
exports
test;
initialization
f := TStringList.Create;
f.Add('temp.txt');
finalization
f.Clear;
f.Free;
end.
--- End code ---
--- Code: ---program test;
{$apptype console}
function test: string; external 'libtest.dll' name 'test';
begin
writeln(test);
end.
--- End code ---
And result stuff:
--- Code: ---C:\Documents and Settings\ADMIN\Pulpit\lib>test
temp.txt
Runtime error 216 at $7C91AC4A
$7C91AC4A
$7C901046
$00405B18
$00407971
--- End code ---
What I'm doing wrong?
Best regards
Maciej
edit:
another two function:
--- Code: --- works well
function test: ansistring;
var
x: TStringList;
begin
x := TStringList.Create;
x.Append('test');
Result := ansistring('test');
x.Free;
end;
--- End code ---
--- Code: --- crash
function test: ansistring;
var
x: TStringList;
begin
x := TStringList.Create;
x.Append('test');
Result := ansistring(x.Text);
x.Free;
end;
--- End code ---
Leledumbo:
--- Quote ---What I'm doing wrong?
--- End quote ---
Returning strings from function (also applies to passing them as parameters). Strings are managed types and they use reference counting in the implementation. When you program dynamic libraries, you should only pass/return basic types. Use PChar as a replacement for strings, i.e. you're now the one responsible for managing the storage (de)allocation and grow/shrink.
--- Quote ---works well
--- End quote ---
Just a lucky coincidence
--- Quote ---crash
--- End quote ---
As expected
Maciej Kaczkowski:
Thanks! I will try as you explained.
edit: It works!
in dll
--- Code: ---function test2: PChar; cdecl;
var
x: TStringList;
r: AnsiString;
begin
x := TStringList.Create;
x.Append('test1234');
r := x.Text+#0;
Result := StrAlloc(Length(r));
StrCopy(Result,PChar(r));
x.Free;
end;
procedure FreePChar(p: PChar);
begin
StrDispose(p);
end;
--- End code ---
in exe
--- Code: ---function test2: PChar; external 'libtest.dll';
var
s: PChar;
begin
s := test2;
WriteLn(s);
FreePChar(s);
end.
--- End code ---
Navigation
[0] Message Index