-1

I am developing a Delphi XE6 application and I created a DLL and the calling EXE application.

Let's say a DLL exports the following method:

procedure GetBuffer(out_buffer: PChar; out_buffer_length: integer); stdcall; export;

The calling application will usually need to do something like this to retrieve the content of the buffer:

// Call #1 => get the length of the buffer
GetBuffer(nil, aLength);
// Allocate memory
SetLength(aBuffer, aLength);
// Call #2 => get the actual content
GetBuffer(aBuffer, aLength);

What if this buffer is the content of a file, and it has changed between Call #1 and Call #2: the resulting aBuffer might be truncated.

What would be the best way to make an atomic call to GetBuffer in that scenario ?

jonjbar
  • 3,896
  • 1
  • 25
  • 46
  • Not sure why this question received a negative vote ? Care to comment so that I can improve it ? – jonjbar Apr 29 '15 at 08:09

1 Answers1

0

If the content you are requesting can change between calls, then I think your current design is not very tenable. I would replace it with a design based on a single call. Use the COM BSTR type to facilitate this. That is wrapped in Delphi by the WideString type.

procedure GetBuffer(out buffer: WideString); stdcall;

Since the COM BSTR is allocated on the shared COM heap, it is safe to have the string allocated in the DLL, and then deallocated in the host executable.

You should avoid using WideString as a function return type because of the problems discussed here: Why can a WideString not be used as a function return value for interop? An out parameter, as I show above, is fine.

As a minor aside, the export keyword has no meaning in Delphi anymore, and should be removed to avoid confusion.

Community
  • 1
  • 1
David Heffernan
  • 601,492
  • 42
  • 1,072
  • 1,490
  • Thank you @David. I understand from a previous reply of yours that using WideString is easy but has implications: linking to OleAut32.dll and performance mainly. http://stackoverflow.com/a/9331077/184404 It that the best way to handle this problem ? Do you have any idea of how does other APIs usually handle this ? – jonjbar Apr 29 '15 at 08:11
  • If you are reading a file, then the minor perf implications of BSTR are irrelevant. I would definitely use BSTR here. Otherwise you need a much more complex api. – David Heffernan Apr 29 '15 at 08:13