Link to home
Start Free TrialLog in
Avatar of corletted

asked on

How To/Best Practices: Passing Strings from C++ DLL to VB calling Application:

My problem is passing strings back to VB from a DLL i wrote in C++.  I have an API for some software written all in C, my desire was to wrap this api into a DLL so that I can use it in my VB app. I just want to be able to pass strings of variable length from the C++ DLL to VB. The C++ will be generating reponses in the form
of strings that are passed back to the VB app. I have read everything I can get my hands on and have not been able to get it to work. Here are my VB and C++ functions.

ERROR: The error I am getting is that the string is not getting returned correctly through GetFilename. I know that filename in the DLL gets set using
SetFilename and contains the string I passed in SetFilename. When I call GetFilename the correct string is printed in the message box. When
I try to print the string returned from GetFilename in the VB app, it contains junk. Consistently its the letter "d", cant figure it out.

P.S. I also have some persistant data structures in my DLL, I have very limited knowledge about memory models and windows programming. Is it ok to have
a persistant datastructure in a DLL. I read that DLLs have to be thread safe? I can guarantee only one app will be calling this DLL.

VB Code.
Private Declare Function SetFilename Lib "MyDLL.DLL" (ByVal S As String) As Long
Private Declare Function GetFilename Lib "MyDLL.DLL" () As String

Private Sub Command1_Click()    
    'I am just taking in the string from a text box
    SetFilename (CStr(Text1.text))
    Dim Temp as String
    Temp = GetFilename
End Sub

C++ Code (portion reponsible for the string being passed to VB)

char            *filename=NULL;

long _stdcall SetFilename(BSTR StringFromVB){
     filename = new char[strlen((LPSTR)(StringFromVB)) + 1];
     return 0;

BSTR _stdcall GetFilename(){

Avatar of jkr
Flag of Germany image

Check out;en-us;187912 ("How To Pass a String Between Visual Basic and Your C DLL") - this works without BSTRs.
Avatar of corletted


I seem to get results with the following changes.  I dont want to cause memory leaks, can someone verify the following solution?


char * filename=NULL;

Private Declare Function GetDictionary Lib "MyDLL.DLL" _
                        (ByVal tempStr As String) As String

char* _stdcall GetDictionary( char* snmpmsg){
      strcpy(snmpmsg, filename);
                return snmpmsg;
  none of those examples address how to pass strings from the C++ DLL "to" the VB app.
  I have not problems passing strings to the C++ DLL "from" the VB app.

did I missing something on those articles?
Avatar of jkr
Flag of Germany image

Link to home
This solution is only available to members.
To access this solution, you must be a member of Experts Exchange.
Start Free Trial
Thanks alot
BTW, you definitely should check the buffer size passed in - insufficiant buffers can cause a lot of headache.