Simple C++ DLL for Visual Basic 6.0

For that past few month or so I have been learning to make DLLs to use with Visual Basic, and in the process learning C++. The benefits of using C++ over Visual Basic is that division and multiplication can be up to 28x faster than the default Visual Basic method.

So I decided to write up a tutorial for others to make their own Visual Basic DLLs. First of all you need to understand the type differences between Visual Basic and Visual C++. The following list has the Visual Basic variable types on the left, and their C++ variable type equivalents on the right.

Integer > short

Long > long

Single > float

Double > double

Byte > unsigned char

String > BSTR

A BStr is a special COM object, which starts with a 4 byte integer for the length, and ends with two terminal string characters. It should also be noted that C++ is case sensitive, so the variable types on the right are how they should be in C++.

Now to create the DLL, open up a copy of Microsoft Visual C++ and select “Win32 Dynamic Link Library” for a new project and call it “Example”. An “Empty Application” will do for what we’re making when the “AppWizard” pops up.

With this new project created, goto the Project menu and add a new file, we need a new source file, I called mine “Main.cpp” but anything will do. Fill the new source file with the following source code.

//
//
#include <windows.h>
 
//
//
long _stdcall Multiply( long A, long B )
{
	return A * B;
}
 
//
//
long _stdcall Divide( long A, long B )
{
	return A / B;
}
 
//
//
long _stdcall SumOf( long A, long B )
{
	return A + B;
}

 

We include the Windows header since we may want to use APIs and because the BSTR is defined in there. The “_stdcall” is used to tell the compiler we want the parameters of the function pushed onto the stack in left to right order.

Now add a new module definition file to the Visual C++ project, call it “Example.def“. This file will let the compiler know what functions we want available to external programs, so after LIBRARY we put the name of our DLL, and under the EXPORTS section we put our available functions, “Multiply”, “Divide” and “SumOf”.

LIBRARY "Example"
EXPORTS
Multiply
Divide
SumOf

 

Finally in your Visual Basic project in the Form_Load() function, we can declare the functions within our DLL and make a call to them. Below shows can example of using the Multiply() function and then outputting it using a message box.

Private Declare Function Multiply Lib "Example" (ByVal A As Long, ByVal B As Long) As Long
Private Declare Function Divide Lib "Example" (ByVal A As Long, ByVal B As Long) As Long
Private Declare Function SumOf Lib "Example" (ByVal A As Long, ByVal B As Long) As Long
 
Private Sub Form_Load()
	Dim i As Long
	i = Multiply(2, 6)
	MsgBox i, vkOkOnly, App.Title
End Sub

 

If all goes correctly, a message box should appear with the value “12” shown.

That’s all for this tutorial, I hope you found it useful.