R – How to return a PChar from a DLL function to a VB6 application without risking crashes or memory leaks


I have to create a DLL which is used by a VB6 application. This DLL has to provide several functions, some of them must return strings.

This is the VB6 declaration:

Declare Function MyProc Lib "mylib.dll" (ByVal Param As String) As String

And this the Delphi implementation stub in mylib.dll:

function MyProc(AParam: PChar): PChar; stdcall;
  ReturnValue: string;
  ReturnValue := GetReturnValue(AParam);
  Result := ???;

What do I have to return here? Who will free the memory of the returnd PChar string?

EDIT: I'm asking about Delphi 2005 (PChar = PAnsiChar)

Best Solution

You need to craft a BSTR instead. VB6 strings are actually BSTRs. Call SysAllocString() on the Delphi side and return the BSTR to the VB6 side. The VB6 side will have to call SysFreeString() to free the string - it will do it automatically.

If PChar corresponds to an ANSI string (your case) you have to manually convert it to Unicode - use MultiByteToWideChar() for that. See this answer for how to better use SysAllocStringLen() and MultiByteToWideChar() together.

Related Question