How can I return a PChar from a DLL function to a VB6 application without risking crashes or memory leaks?

前端 未结 7 1510
花落未央
花落未央 2020-12-19 05:37

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:<

7条回答
  •  旧时难觅i
    2020-12-19 06:17

    I would say that whoever allocates the memory must also free it in this case. You will run into problems with other scenarios. So the most safe and clean way would be:

    1. The DLL allocates memory (because it knows how much) and returns the PChar to caller
    2. After the caller is done with it, it calls FreePointer back to the DLL
    3. DLL frees the memory in the FreePointer exported function

    The setup would be like this:

    unit DLL;
    
    interface
    
    uses
      SysUtils;
    
    function Execute(const Params: PChar): PChar; stdcall;
    procedure FreePointer(const P: PChar); stdcall;
    
    exports Execute;
    exports FreePointer;
    
    implementation
    
    function Execute(const Params: PChar): PChar; stdcall;
    var
      Size: Cardinal;
    begin
      Size := Calculate the size;
      GetMem(Result, Size);
    
      ...do something to fill the buffer
    end;
    
    procedure FreePointer(const P: PChar); stdcall;
    begin
      FreeMem(P);
    end;
    
    end.
    

提交回复
热议问题