Search code examples
delphidelphi-xe7dllexport

DLL export issues with PAnsiChar in Delphi XE7 using stdcall convention


I have a DLL- which has a function

Decrypt(aText, aKey: PAnsiChar): PAnsiChar; stdcall

and this function has been exported. as

exports
  Decrypt;

And If I call from client in below way:

lH :=  LoadLibrary('EncDec.dll');
FEncDyc := GetProcAddress(lH , PChar('Decrypt'));

lResult := FEncDyc(PAnsiChar(AnsiString(EditPwd.Text)), 
    PAnsiChar(AnsiString(EditKey.Text)));

where FEncDyc is a pointer to func of type

TDecrypt =  function (aText: PAnsiChar; aKey: PAnsiChar): PAnsiChar;

I always get Junk values for parameters aText and aKey; where am I going wrong? if I change the definition of dll to

Decrypt(aText, aKey: PAnsiChar): PAnsiChar; export;

I get values in the DLL with no junk characters- works fine!

Whats wrong in the code for an stdcall and what does it make difference if I use export key instead.

Also please suggest: Whats the right way to pass PAnsiChar and how to typecast it to AnsiString in my dll.


Solution

  • You failed to specify the calling convention when importing. Instead of

    TDecrypt = function(aText: PAnsiChar; aKey: PAnsiChar): PAnsiChar;
    

    you need

    TDecrypt = function(aText: PAnsiChar; aKey: PAnsiChar): PAnsiChar; stdcall;
    

    Do be careful with the return value. You have to ensure that the value that you return is allocated dynamically using GetMem or equivalent. And you also need to export a deallocator from the DLL.