Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Get string return value from C DLL in Delphi

Tags:

c

dll

delphi

I have a legacy DLL written in C that contains a function that returns a string, and I need to access this function from Delphi. The only info I have about the DLL is the VB declare for accessing the function:

Public Declare Function DecryptStr Lib "strlib" (Str As String) As String

I've tried the following without success:

Declaration:

function DecryptStr(s: PChar): PChar; cdecl; external 'strlib.dll';

Usage:

var
  p1, p2 : pchar;
begin
  GetMem( p1, 255 );
  StrPCopy( p2, 'some string to decrypt' );
  p1 := DecryptStr( p2 );
end;

This consistently crashes the DLL with an Access Violation. I'm at a loss.

Any suggestions ?

like image 699
Kevin McBrearty Avatar asked Dec 18 '22 10:12

Kevin McBrearty


1 Answers

Consider rewriting your test code as follows:

var
  p1, p2 : pchar;
begin
  GetMem( p1, 255 ); // initialize
  GetMem( p2, 255 );
  StrPLCopy( p2, 'some string to decrypt', 255 ); // prevent buffer overrun
  StrPLCopy( p1, DecryptStr( p2 ), 255); // make a copy since dll will free its internal buffer
end;

If still fails within a call to DecryptStr, then read http://support.microsoft.com/kb/187912 carefully.

like image 134
andrius Avatar answered Dec 24 '22 02:12

andrius