How do I pass and retrieve memory stream from my Application to/from DLL?

前端 未结 3 2137
心在旅途
心在旅途 2021-02-10 16:54

Suppose I have a TMemoryStream I need to pass to my DLL and get back TMemoryStream (Bitmap stream) from the DLL.

I was thinking my DLL would ha

3条回答
  •  时光取名叫无心
    2021-02-10 17:19

    Two obvious options, assuming the callee is to allocate the memory:

    1. Use a shared heap

    For instance you can use the COM heap. In the callee your write:

    OutBuffSize := ...; // you know what this value is
    OutBuff := CoTaskMemAlloc(OutBuffSize);
    // populate the buffer
    

    The caller destroys this with CoTaskMemFree. You can use LocalAlloc, or HeapAlloc if you prefer, it doesn't really matter.

    2. Use the callee's heap and export a deallocator

    Here you use the native heap of the callee:

    OutBuffSize := ...; // you know what this value is
    GetMem(OutBuff, OutBuffSize);
    // populate the buffer
    

    You also need to export a deallocator:

    procedure DeallocateMemory(Ptr: Pointer); stdcall;
    begin
      FreeMem(Ptr);
    end;
    

    Another option that I rejected is to use a shared memory manager. I tend to avoid that because it constrains the caller to be a Delphi program.

    To fill a stream from a buffer call WriteBuffer:

    Stream.WriteBuffer(Buff^, BuffSize);
    

    where Buff is a pointer to the buffer.

提交回复
热议问题