1. Use the menus: New\Projects\Win32 Dynamic-Link Library. Enter the directory
where you want the VC++ project and the project name (MyFuncsProject in the
example).
2. New\Files\C++ Source File. Check the Add To Project box. Enter the file name
(MyFuncs.cpp in the example).
3. Enter the function's source code. Use __declspec to export the function's
symbol. Use 'extern "C"' to minimize name mangling by VC++.
// Prototype the function.
// Use 'extern "C"' to minimize name mangling.
extern "C" DllExport long MyCFunc(long x);
// Define the function.
extern "C" DllExport long MyCFunc(long x)
{
return x * x;
}
4. Set project options using Project\Settings. On the C/C++ tab, select the
Code Generation category. Then change Calling Convention to __stdcall.
5. Select Build\Set Active Configuration. Select the Release configuration.
Repeat step 4 to make the options apply to the release configuration in addition
to the debug configuration. Use Build\Set Active Configuration to reselect the
debug configuration if desired.
6. Build the project (press F7 or use the Build menu). This creates the
DLL file.
7. In your Visual Basic program, declare the DLL function using the DLL file's
full path name. The function's name in the DLL file has been slightly mangled by
VC++. The name is an underscore, followed by the name you gave it, followed by
"@", followed by the number of bytes in the function's argument list. In this
example the name is _MyCFunc@4 because the function takes one 4 byte argument
(a long integer).
Private Declare Function MyCFunc Lib _
"C:\VBHelper\VcDll\Method1\Release\MyFuncsProject.dll" _
Alias "_MyCFunc@4" _
(ByVal x As Long) As Long
Private Sub Command1_Click()
Dim x As Long
Dim y As Long
x = CInt(Text1.Text)
y = MyCFunc(x)
Label1.Caption = Str$(y)
End Sub
*** HINT: To quickly determine the mangled name of the function, find the DLL
file in Windows Explorer. Right click on the file and select the "Quick View"
command. This presents an editor showing information about the DLL. Page down 2
or 3 pages and you will find a list of exported symbols available in the DLL.
One of these will be the mangled function name.