troubleshooting Question

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

Avatar of corletted
corletted asked on
6 Comments1 Solution374 ViewsLast Modified:
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(){

Join our community to see this answer!
Unlock 1 Answer and 6 Comments.
Start Free Trial
Learn from the best

Network and collaborate with thousands of CTOs, CISOs, and IT Pros rooting for you and your success.

Andrew Hancock - VMware vExpert
See if this solution works for you by signing up for a 7 day free trial.
Unlock 1 Answer and 6 Comments.
Try for 7 days

”The time we save is the biggest benefit of E-E to our team. What could take multiple guys 2 hours or more each to find is accessed in around 15 minutes on Experts Exchange.

-Mike Kapnisakis, Warner Bros