* * *

Author Topic: DLL Problem  (Read 771 times)

cappe

  • New member
  • *
  • Posts: 31
DLL Problem
« on: March 19, 2017, 06:23:51 pm »
I have made a simple DLL with lazarus 1.6.2 with 2 function:

function GetValue : PAnsiChar; cdecl;
var
  aStr : String;
  Temp : PAnsiChar;
begin
   aStr := 'wewewewewewe';
   Result := StrAlloc(Length(aStr));
   Temp := Addr(aStr[1]);
   StrCopy(Result, Temp);
end;

procedure FreeString(strin: PAnsiChar); cdecl;
begin
  StrDispose(strin);
end; 

When I call this function from host program, after some call to these functions, the program closes by itself. Can anyone tell me why? How can I find out why? How can I fix the problem?

Thank you

ASerge

  • Sr. Member
  • ****
  • Posts: 312
Re: DLL Problem
« Reply #1 on: March 19, 2017, 08:10:37 pm »
StrAlloc allocates LENGTH, but StrCopy copies LENGTH + 1 (+ the last zero)

cappe

  • New member
  • *
  • Posts: 31
Re: DLL Problem
« Reply #2 on: March 20, 2017, 10:14:45 am »
StrAlloc allocates LENGTH, but StrCopy copies LENGTH + 1 (+ the last zero)
I tried to change the code, but the program stops after a few calls to the dll. How can I fix the problem?

ASerge

  • Sr. Member
  • ****
  • Posts: 312
Re: DLL Problem
« Reply #3 on: March 20, 2017, 06:07:37 pm »
How can I fix the problem?
The error in another place, as the saying goes, in line 13 :)
Lib:
Code: Pascal  [Select]
  1. library ProjectLib;
  2.  
  3. uses SysUtils;
  4.  
  5. function GetValue: PAnsiChar; cdecl;
  6. var
  7.   AStr: string;
  8. begin
  9.   AStr := 'wewewewewewe';
  10.   Result := StrAlloc(Length(AStr) + Length(#0));
  11.   StrPCopy(Result, AStr);
  12. end;
  13.  
  14. procedure FreeString(StrIn: PAnsiChar); cdecl;
  15. begin
  16.   StrDispose(StrIn);
  17. end;
  18.  
  19. exports
  20.   GetValue, FreeString;
  21.  
  22. begin
  23. end.

Test (no error):
Code: Pascal  [Select]
  1. program ProjectTestLib;
  2.  
  3. function GetValue: PAnsiChar; cdecl; external 'ProjectLib.dll';
  4. procedure FreeString(StrIn: PAnsiChar); cdecl; external 'ProjectLib.dll';
  5.  
  6. procedure Test;
  7. var
  8.   P: PAnsiChar;
  9.   i: Integer;
  10. begin
  11.   for i := 1 to 10000 do
  12.   begin
  13.     P := GetValue;
  14.     FreeString(P);
  15.   end;
  16. end;
  17.  
  18. begin
  19.   Test;
  20. end.

cappe

  • New member
  • *
  • Posts: 31
Re: DLL Problem
« Reply #4 on: March 21, 2017, 04:25:07 pm »
many many thanks  ;)

ASerge

  • Sr. Member
  • ****
  • Posts: 312
Re: DLL Problem
« Reply #5 on: March 21, 2017, 04:47:53 pm »

 

Recent

Get Lazarus at SourceForge.net. Fast, secure and Free Open Source software downloads Open Hub project report for Lazarus