Tech Support > Microsoft Windows > Development Resources > Visual C++ calling Visual Basic DLL
Visual C++ calling Visual Basic DLL
Posted by Paul on January 21st, 2005


Online, I found an example on how to call Visual Basic DLL from Visual
C++.

http://milinddev.tripod.com/javavbvccall.htm

But the example does not work. Does anyone have an idea on how to call
a Visual Basic DLL from Visual C++ ?

I create the DLL just fine with VB. Then connecting to it using VC++
seems impossible.

Thanks.

Posted by Craig Kelly on January 21st, 2005


"Paul" wrote:

[Assuming VB 6]

A VB DLL is an ActiveX DLL, so you can use it just like any other COM
library. Since you mention Visual C++, you can use the #import directive.
You just need to remember that a VB class has a default interface named
_"Class Name". The quick example I just ran:

- Created an ActiveX DLL project in VB named testlib.

- Add a class named test_class (thus the interface will be named
_test_class)

- Add the following function:
Public Function DblStr(ByVal s As String) As String
DblStr = s & s
End Function

- Make the DLL

- Write the following C++ (note: compiled with VC 7, not 6, but it should
work)

#include <windows.h>
#include <string>
#include <iostream>

//This works because VB embeds the typelib in the DLL
#import "testlib.dll" no_namespace

using namespace std;

int main(void)
{
CoInitialize(NULL);

_test_classPtr t;
t.CreateInstance("testlib.test_class");

string s = t->DblStr("Howdy");
cout << "Howdy doubled is : " << s << endl;

t.Release();

CoUninitialize();
return 0;
}



- Build with cl /GX test.cpp

- Output was

Howdy doubled is : HowdyHowdy


Of course, I ignored all errors and problems (I didn't check for a
_com_error exception getting thrown, the _bstr_t char* operator I used to
create string s could have returned a NULL which would have been bad, etc,
etc).

Craig




Similar Posts