Browse DevX
Sign up for e-mail newsletters from DevX

Tip of the Day
Language: VBA
Expertise: Intermediate
Apr 1, 2008

Passing Strings Between Delphi DLL and VBA

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 string
StrDataSizePtr:^Longword;    //pointer to 4-byte memory size--later,
                             //we will make it point to the BSTR 
                             //string size location
   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. 

GetStr name 'GetStr';

To use the DLL in VBA (assuming the DLL is in C:\Program Files\Common Files), the declaration would be:

Public Declare Sub GetStr Lib "C:\Program Files\Common Files\Example.dll" 
(ByVal A As String, ByVal B As String)

Public Sub Test_GetStr()
Dim A As String
Dim B As String

A="This is a test..."
B = String(100, vbNullChar) 'reserve lots of space for B
GetStr A, B
MsgBox "-" & B & "-"

End Sub
Romeo Besas
Thanks for your registration, follow us on our social networks to keep up-to-date