Unlike other routines, this one doesn’t need to pass the length of the returned string for later trimming in VBA. This is because the Delphi function also tricks VBA into “thinking” the returned string is Length(tmpStr) long when, in reality, it is really still 100-characters long. The trick has to be done though, so that all the nulls after the “0” (zero) character are ignored.
Here’s the Delphi DLL:
Library Example;uses SysUtils;procedure GetStr(A: PChar; B: PChar);stdcall;var StrData:Longword absolute B; //make StrData share B's memory so it //also holds the address of the first //character in the stringStrDataSizePtr:^Longword; //pointer to 4-byte memory size--later, //we will make it point to the BSTR //string size locationtmpStr:string;begin tmpStr:=A; tmpStr:=tmpStr + '1234567890'; //make changes to tmpStr StrPLCopy(B,tmpStr, Length(tmpStr)); //Copy tmpStr to B StrDataSizePtr:=Ptr(StrData-4); //point string size location //which starts 4 bytes before //the first char in the string StrDataSizePtr^:=Length(tmpStr); //set size to tmpStr length. //this tricks VBA into reading //only length(tmpStr) chars. end;exportsGetStr name 'GetStr';beginend
To use the DLL in VBA (assuming the DLL is in C:Program FilesCommon Files), the declaration would be:
Public Declare Sub GetStr Lib "C:Program FilesCommon FilesExample.dll" (ByVal A As String, ByVal B As String)Public Sub Test_GetStr()Dim A As StringDim B As StringA="This is a test..."B = String(100, vbNullChar) 'reserve lots of space for BGetStr A, BMsgBox "-" & B & "-"End Sub