Search code examples
c++delphiwinapidlldelphi-6

Using C++ DLL in Delphi 6


I have to use an encoding function from an external C++ DLL in Delphi 6. Following is the declaration provided :

long <Function Name> (char *Data, long &Apply, char *ReturnVal, long &Size)

Data is the input value, Apply is a boolean value (default : FALSE), ReturnVal is the return value from the DLL and Size is the length of the ReturnVal.

To use this in Delphi 6, I wrote following Code:

implementation
   const
     EncoderDLL = '<DLL NAME>';
     FunctionName = 'FUNCTION NAME';
   var
      _TEST : function(const Data : PChar; Apply : PInteger;stOutput : Pchar;
          iSize : PInteger) : integer; stdcall;
   .....
   .....
   var
     stInput,stOutput : string;
     iLength,i1,iResult : integer;
     hnd : THandle;
   begin
     iLength := 0;
     i1 := 0;
     stInput := Trim(edtInput.Text);
     hnd := SafeLoadLibrary(EncoderDLL);
     if hnd > 0 then
     begin
       @_TEST := GetProcAddress(hnd,FunctionName);
       if @_TEST <> nil then
       begin
         iResult := _TEST(PChar(stInput),@i1,PChar(StOutput),@iLength); // ERROR
       end;
     end;
     FreeLibrary(hnd);
  end;

I am getting Access Violation in the line having 'ERROR' as comments.

If I replace PChar in the function declaration with string, then the access violation does not come at the same line. It comes while freeing the library. Also, the value of the iLength parameter is populated correctly.

Can anyone please provide pointers to resolve this issue.


Solution

  • Keep PChar, and initialize StOutput to a non-empty string (of a sufficient length) before the call.