David's answer to another question shows a Delphi DLL function returning a WideString. I never thought that was possible without the use of ShareMem
.
My test DLL:
function SomeFunction1: Widestring; stdcall;
begin
Result := 'Hello';
end;
function SomeFunction2(var OutVar: Widestring): BOOL; stdcall;
begin
OutVar := 'Hello';
Result := True;
end;
My caller program:
function SomeFunction1: WideString; stdcall; external 'Test.dll';
function SomeFunction2(var OutVar: Widestring): BOOL; stdcall; external 'Test.dll';
procedure TForm1.Button1Click(Sender: TObject);
var
W: WideString;
begin
ShowMessage(SomeFunction1);
SomeFunction2(W);
ShowMessage(W);
end;
It works, and I don't understand how. The convention I know of is the one used by the Windows API, for example Windows GetClassNameW
:
function GetClassNameW(hWnd: HWND; lpClassName: PWideChar; nMaxCount: Integer): Integer; stdcall;
Meaning the caller provides the buffer, and the maximum length. The Windows DLL writes to that buffer with the length limitation. The caller is allocates and deallocates the memory.
Another option is that the DLL allocate the memory for example by using LocalAlloc
, and the Caller deallocates the memory by calling LocalFree
.
How does the memory allocation and deallocation work with my DLL example? Does the "magic" happen because the result is WideString
(BSTR
)? And why aren't Windows APIs declared with such convenient convention? (Are there any known Win32 APIs that uses such convention?)
EDIT:
I Tested the DLL with C#.
Calling SomeFunction1
causes an AV (Attempted to read or write protected memory
).
SomeFunction2
works fine.
[DllImport(@"Test.dll")]
[return: MarshalAs(UnmanagedType.BStr)]
static extern string SomeFunction1();
[DllImport(@"Test.dll")]
[return: MarshalAs(UnmanagedType.Bool)]
static extern bool SomeFunction2([MarshalAs(UnmanagedType.BStr)] out string res);
...
string s;
SomeFunction2(out s);
MessageBox.Show(s); // works ok
MessageBox.Show(SomeFunction1()); // fails with AV!
Here is a followup.
CoTaskMemAlloc
. does Delphi call it when allocationWideString
? also, when does theCoTaskMemFree
called? – Surpass