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 ?
Consider rewriting your test code as follows:
If still fails within a call to DecryptStr, then read http://support.microsoft.com/kb/187912 carefully.
I agree with CesarB, try to declare it with stdcall directive as:
if it doesn't work, post the VB declaration here.
The suggestions that the strings must be "initialised" seem to be correct. This is because C will require that the string being passed in is null-terminated. Check that the character in the bufffer just after the end of the text is a null (#0).
Why do you assume that the string passed in is exactly 255 chars long? You need to allocate Length(p1) + 1 bytes - for the chars in p1, and a #0 char at the end.
Also, your code sample seems confused as to the use of p1 and p2. It looks like p1 is the buffer passed to the C DLL, which you allocate, and p2 is the returned string that the DLL allocates. But then the code would be (note use of p1 and p2)
Better variable names would help you make this clearer.