Microsoft KB Archive/181578

= How To Callback Visual Basic Functions From a C DLL =

Article ID: 181578

Article Last Modified on 6/29/2004

-

APPLIES TO


 * Microsoft Visual Basic 5.0 Learning Edition
 * Microsoft Visual Basic 5.0 Professional Edition
 * Microsoft Visual Basic 5.0 Enterprise Edition

-



This article was previously published under Q181578



SUMMARY
With the new AddressOf operator in Microsoft Visual Basic 5.0, you can pass a DLL the pointer to a Microsoft Visual Basic function and have the DLL call that function through the pointer. This article gives you some sample code to get started and also demonstrates how to pass strings from your DLL to Microsoft Visual Basic.



MORE INFORMATION
To use this article, follow the steps below to create a Microsoft Visual Basic 5.0 .exe project and a Microsoft Visual C++ 5.0 .dll project. Then run your Microsoft Visual Basic program to test it.

Steps to Create the Microsoft Visual Basic 5.0 Project
 Create a new Standard EXE project in Microsoft Visual Basic 5.0. Add a Command button to Form1.  Add the following declare statement to the General Declarations section of Form1: Private Declare Sub ExecuteCallback Lib "vcvbdll" ( _        ByVal pFunc as Long)

  Add the following code to the Click event of the Command button: Call ExecuteCallback(AddressOf MyCallback)

  Add a new module to the project, and add the following code to the module. Sub MyCallback(ByVal parm as String) MsgBox "You are inside the VB callback function!" MsgBox "Parameter passed in was: " & parm End Sub



Steps to Create the Microsoft Visual C++ 5.0 Project
 Create a new Microsoft Visual C++ 5.0 MFC AppWizard (dll) project named "vcvbdll" and accept all of the default options.</li>  Add the following code to the end of the vcvbdll.cpp file: void __stdcall ExecuteCallback(long cbAddress) { // Declare the function pointer, with one string argument. typedef void (__stdcall *FUNCPTR)(BSTR pbstr); FUNCPTR vbFunc;

// Point the function pointer at the passed-in address. vbFunc = (FUNCPTR)cbAddress;

// Call the function through the function pointer. vbFunc(SysAllocString(L"Hi! This message came from your DLL!")); }

</li>  Add the following line to the end of the vcvbdll.def file to export the ExecuteCallback function: ExecuteCallback

</li> Compile the project, and copy the .dll to the \Windows\System directory to test it.</li></ol>

<div class="references_section">