Creating A Windows DLL With Visual Basic
Creating A Windows DLL With Visual Basic
A dynamic link library may include internal functions, which can be called only from within the DLL. Its main purpose, however, is to provide exported functions--that is, functions that reside in a module of the DLL and can be called from other DLLs and applications. Frequently, a definition (.def) file is used in C/C++ projects to list a DLL's exports. A DLL also includes an optional entry point, which is called when a process or thread loads or unloads the DLL. Windows calls this entry point when a process loads and unloads the DLL. It also calls the entry point when the process creates or terminates a thread. That allows the DLL to perform any per-process and per-application initialization and cleanup. The syntax of this entry point, which must use the standard-call calling convention (used by default in Visual Basic), is:
Public Function DllMain(hinstDLL As Long, fdwReason As Long, lpwReserved As Long) As Boolean
a Long containing the instance handle of the DLL. This is the same as the DLL's module handle. a constant indicating why the entry point has been called. Possible values are:
fdwReason,
DLL_PROCESS_ATTACH (1)
The process is spawning a new thread. Any per-thread initialization should be performed.
DLL_THREAD_DETACH (3)
A process is detaching the DLL, or the process is exiting. Any per-process cleanup should be performed.
lpvReserved
A Long that provides more information about DLL_PROCESS_ATTACH and DLL_PROCESS_DETACH. (It is unused if fdwReason is DLL_THREAD_ATTACH or DLL_THREAD_DETACH.) If fdwReason is DLL_PROCESS_ATTACH, it is Nothing for libraries loaded dynamically using functions like LoadLibrary and GetProcAddress, and it is not Nothing for libraries loaded statically by providing library stubs at compile time. If fdwReason is DLL_PROCESS_DETACH, it is Nothing if the call has resulted from a call to the Win32 FreeLibrary function, and it is not Nothing if the entry point is called during process termination. The return value of the function is meaningful only if fdwReason is DLL_PROCESS_ATTACH. If initialization succeeds, the function should return True; otherwise, it should return False. Note that because the function is an entry point called by Windows, the values of the arguments passed to the function are provided by Windows. Also, the entry point is not called when a thread is terminated using the Win32 TerminateThread function, nor is it called when a process is terminated using the Win32 TerminateProcess function.
the DLL's code, which we'll store in a code module (a .bas file) named MathLib:
Option Explicit Public Public Public Public Const Const Const Const DLL_PROCESS_DETACH = 0 DLL_PROCESS_ATTACH = 1 DLL_THREAD_ATTACH = 2 DLL_THREAD_DETACH = 3
Public Function DllMain(hInst As Long, fdwReason As Long, lpvReserved As Long) As Boolean Select Case fdwReason Case DLL_PROCESS_DETACH ' No per-process cleanup needed Case DLL_PROCESS_ATTACH DllMain = True Case DLL_THREAD_ATTACH ' No per-thread initialization needed Case DLL_THREAD_DETACH ' No per-thread cleanup needed End Select End Function Public Function Increment(var As Integer) As Integer If Not IsNumeric(var) Then Err.Raise 5 Increment = var + 1 End Function Public Function Decrement(var As Integer) As Integer If Not IsNumeric(var) Then Err.Raise 5 Decrement = var - 1 End Function Public Function Square(var As Long) As Long If Not IsNumeric(var) Then Err.Raise 5 Square = var ^ 2 End Function
Several characteristics about the code are worth mentioning. The first is that although it includes a DllMain procedure, no per-process or per-thread initialization needs to be performed. So DllMain simply returns True if it is called with the fdwReason argument set to DLL_PROCESS_ATTACH. Second, the point of providing a Windows DLL is to allow other languages to call it. To ensure interoperability, we want to confine ourselves to language features that the Win32 API supports, so that our DLL can be called from as many development environments and platforms as possible. We could have made each of our three math functions more flexible, for example, by defining both the incoming argument and the return value as Variants. That would have allowed the function to determine the data type it should interpret the incoming data as, in addition to the data type it should return. But the Variant is a data type defined by COM, Microsoft's Component Object Model, and is not a data type Win32 API recognizes. So instead, the code uses standard Win32 API data types. We'll also need a test program to tell us whether our Windows DLL is working properly. For that purpose, we
can create a Standard EXE project with one form and one code module. The code module simply consists of the Declare statements that define the functions found in the DLL:
Public Declare Function Increment Lib "MathLib.dll" (var As Integer) As Integer Public Declare Function Decrement Lib "MathLib.dll" (var As Integer) As Integer Public Declare Function Square Lib "MathLib.dll" (var As Long) As Long
Rather than simply specifying the name of the DLL in the Lib clause, you also should add the full path to the directory that contains the DLL. The form's code performs the calls to the DLL functions:
Option Explicit Dim incr As Integer Dim decr As Integer Dim sqr As Long Private Sub cmdDecrement_Click() decr = Increment(decr) cmdDecrement.Caption = "x = " & CStr(decr) End Sub Private Sub cmdIncrement_Click() incr = Increment(incr) cmdIncrement.Caption = "x = " & CStr(incr) End Sub Private Sub cmdSquare_Click() sqr = Square(srr) cmdSquare.Caption = "x = " & CStr(sqr) End Sub Private Sub Form_Load() incr = 1 decr = 100 sqr = 2 End Sub
Figure 1. Error when accessing an ActiveX DLL as a Windows DLL The most likely cause of this error is that the function is not actually exported by the DLL. We can use the DumpBin utility to examine a DLL's exports by using the syntax
Dumpbin <path and name of dll> /exports
Dump of file mathlib.dll File Type: DLL Section contains the following exports for MathLib.dll 0 41B9E52C 0.00 1 4 4 characteristics time date stamp Fri Dec 10 10:04:28 2004 version ordinal base number of functions number of names name DllCanUnloadNow DllGetClassObject DllRegisterServer DllUnregisterServer
ordinal hint RVA 1 2 3 4 Summary 1000 1000 1000 1000 .data .reloc .rsrc .text 0 1 2 3 0000192E 00001902 00001918 000018EC
Our DLL exports four functions, all of which are utility functions that support COM. Clearly we need to export DllMain and our three math functions. But how? Visual Basic does not appear to allow you to export DLL
functions from ActiveX DLLs, thus effectively preventing you from using Visual Basic to create a standard Windows DLL. This difficulty, however, is not insurmountable. When we select the File -> Make <filename>.dll menu option to create an ActiveX DLL, it appears that Visual Basic is seamlessly taking our source code and outputting an ActiveX DLL. But if we examine the subdirectory in which Visual Basic was installed, it appears that the process is not quite so seamless. Along with VB6.EXE, the Visual Basic executable that defines the Visual Basic environment, we can also find C2.EXE and LINK.EXE, which are a compiler and a linker, respectively. Their presence in this directory suggests that VB6.EXE itself does not handle the generation of a DLL file, but that at some point in the compilation process, it calls these programs. We can find out how Visual Basic is using the compiler and linker more precisely by renaming them and creating wrapper executables named C2 and LINK that in turn call the real compiler and linker. The following is the source code for a new version of a console-mode C2.EXE that calls the "real" C2 compiler, which we've renamed C2comp.exe:
Public Sub Main() On Error Resume Next Dim strCmd As String, strPath As String Dim oFS As New Scripting.FileSystemObject Dim ts As TextStream strCmd = Command strPath = App.Path Set ts = oFS.CreateTextFile(strPath & "\c2log.txt") ts.WriteLine "Beginning execution at " & Date & " " & Time() ts.WriteBlankLines 1 ts.WriteLine "Command line parameters to c2 call:" ts.WriteLine " " & strCmd ts.WriteBlankLines 1 ts.WriteLine "Calling C2 compiler" Shell "c2comp.exe " & strCmd If Err.Number <> 0 Then ts.WriteLine "Error in calling C2 compiler..." End If ts.WriteBlankLines 1 ts.WriteLine "Returned from c2 compiler call" ts.Close End Sub
The process of compiling an ActiveX DLL produces the following output in our log file:
Beginning execution at 12/10/2004 12:44:22 PM
Command line parameters to c2 call: -il "C:\DOCUME~1\Ron\LOCALS~1\Temp\VB277103" -f "C:\VB Projects\ MathLib\MathMod.bas" -W 3 -Gy -G5 -Gs4096 -dos -Zl -Fo"C:\ VB Projects\MathLib\MathMod.OBJ" -QIfdiv -ML -basic Calling C2 compiler Returned from c2 compiler call
These are fairly standard command-line arguments to produce object files that in turn are supplied to the linker. That means that to determine how to produce a Windows DLL, we'll have to intercept the call to the linker so that we can see what arguments Visual Basic passes to it. The following code does that:
Public Sub Main() On Error Resume Next Dim strCmd As String, strPath As String Dim oFS As New Scripting.FileSystemObject Dim ts As TextStream strCmd = Command strPath = App.Path Set ts = oFS.CreateTextFile(strPath & "\lnklog.txt") ts.WriteLine "Beginning execution at " & Date & " " & Time() ts.WriteBlankLines 1 ts.WriteLine "Command line parameters to LINK call:" ts.WriteLine " " & strCmd ts.WriteBlankLines 1 ts.WriteLine "Calling LINK linker" Shell "linklnk.exe " & strCmd If Err.Number <> 0 Then ts.WriteLine "Error in calling linker..." Err.Clear End If ts.WriteBlankLines 1 ts.WriteLine "Returned from linker call" ts.Close End Sub
It requires that we rename the linker LinkLnk.exe and name our link wrapper Link.exe. When we attempt to compile an ActiveX DLL project, our linker log file contains the following output:
Beginning execution at 12/11/2004 12:44:33 PM Command line parameters to LINK call:
Command line parameters to LINK call: "C:\Program Files\Microsoft Visual Studio\VB98\Class1.OBJ" "C:\Program Files\Microsoft Visual Studio\VB98\Project1.OBJ" "C:\Program Files\Microsoft Visual Studio\VB98\VBAEXE6.LIB" /ENTRY:__vbaS /OUT:"C:\Program Files\Microsoft Visual Studio\VB98\Project1.dll" /BASE:0x11000000 /SUBSYSTEM:WINDOWS,4.0 /VERSION:1.0 /DLL /INCREMENTAL:NO /OPT:REF /MERGE:.rdata=.text /IGNORE:4078 Calling LINK linker Returned from linker call
If we compare these command-line arguments with the syntax required to link the object files for a DLL using either C or C++, an omission becomes immediately apparent. Although the /DLL switch is supplied to create a standard DLL, there is no /DEF switch to define a module definition (.def) file that lists the functions exported by the DLL. (If we were programming in C or C++, we could use statements within our code to define our exports. Visual Basic doesn't support this, however, making the .def file the sole means of defining a library's exports.) Moreover, if we examine the files generated for an ActiveX DLL project by the Visual Basic environment, we'll also find that Visual Basic itself has not generated a .def file.
The NAME statement defines the name of the DLL. The LIBRARY statement must either precede the list of exported functions or appear on the same line as the first function. The .def file should also list the ordinal position of each exported function preceded by an @ symbol. 2. Decide how we want to intercept the call to the linker. Two major techniques are available to do this: Patching the Import Address Table (IAT), which requires that we build a Visual Basic add-in that modifies the IAT in order to intercept particular calls by Visual Basic to the Win32 API. Although
it's certainly the most elegant method, its complexity makes it a worthy subject for a separate article. Building a proxy linker that intercepts the call to the real linker, modifies the command-line arguments to be passed to the linker, and then calls the linker with the correct command-line arguments. This is the approach we used to discover what arguments Visual Basic was passing to the compiler and linker, and it's the approach we'll adopt to create a Windows DLL. In building our proxy linker, we want a sufficiently flexible design so that we can generate other kinds of files, if need be. 3. Modify the arguments to the linker to add the /DEF switch along with the path and filename of our .def file. To do this, you must create a Visual Basic Standard EXE project, add a reference to the Microsoft Scripting Runtime Library, remove the form from the project, and add a code module. The source code for the proxy linker is as follows:
Option Explicit Public Sub Main() Dim Dim Dim Dim Dim Dim Dim Dim Dim Dim SpecialLink As Boolean, fCPL As Boolean, fResource As Boolean intPos As Integer strCmd As String strPath As String strFileContents As String strDefFile As String, strResFile As String oFS As New Scripting.FileSystemObject fld As Folder fil As File ts As TextStream, tsDef As TextStream
strCmd = Command Set ts = oFS.CreateTextFile(App.Path & "\lnklog.txt") ts.WriteLine "Beginning execution at " & Date & " " & Time() ts.WriteBlankLines 1 ts.WriteLine "Command line arguments to LINK call:" ts.WriteBlankLines 1 ts.WriteLine " " & strCmd ts.WriteBlankLines 2 ' Determine if .DEF file exists ' ' Extract path from first .obj argument intPos = InStr(1, strCmd, ".OBJ", vbTextCompare) strPath = Mid(strCmd, 2, intPos + 2) intPos = InStrRev(strPath, "\") strPath = Left(strPath, intPos - 1) ' Open folder Set fld = oFS.GetFolder(strPath) ' Get files in folder
' Get files in folder For Each fil In fld.Files If UCase(oFS.GetExtensionName(fil)) = "DEF" Then strDefFile = fil SpecialLink = True End If If UCase(oFS.GetExtensionName(fil)) = "RES" Then strResFile = fil fResource = True End If If SpecialLink And fResource Then Exit For Next ' Change command line arguments if flag set If SpecialLink Then ' Determine contents of .DEF file Set tsDef = oFS.OpenTextFile(strDefFile) strFileContents = tsDef.ReadAll If InStr(1, strFileContents, "CplApplet", vbTextCompare) > 0 Then fCPL = True End If ' Add module definition before /DLL switch intPos = InStr(1, strCmd, "/DLL", vbTextCompare) If intPos > 0 Then strCmd = Left(strCmd, intPos - 1) & _ " /DEF:" & Chr(34) & strDefFile & Chr(34) & " " & _ Mid(strCmd, intPos) End If ' Include .RES file if one exists If fResource Then intPos = InStr(1, strCmd, "/ENTRY", vbTextCompare) strCmd = Left(strCmd, intPos - 1) & Chr(34) & strResFile & _ Chr(34) & " " & Mid(strCmd, intPos) End If ' If Control Panel applet, change "DLL" extension to "CPL" If fCPL Then strCmd = Replace(strCmd, ".dll", ".cpl", 1, , vbTextCompare) End If ' Write linker options to output file ts.WriteLine "Command line arguments after modification:" ts.WriteBlankLines 1 ts.WriteLine " " & strCmd ts.WriteBlankLines 2 End If ts.WriteLine "Calling LINK.EXE linker" Shell "linklnk.exe " & strCmd If Err.Number <> 0 Then ts.WriteLine "Error in calling linker..." Err.Clear End If ts.WriteBlankLines 1 ts.WriteLine "Returned from linker call" ts.Close
This proxy linker modifies only the command-line arguments passed to the linker if a .def file is present in the directory that contains the Visual Basic project; otherwise it simply passes the command-line arguments on to the linker unchanged. If a .def file is present, it adds a /DEF switch to the command line. It also determines whether any resource files are to be added to the linked file list. Finally, it examines the export table to determine if a function named CplApplet is present; if it is, it changes the output file's extension from .dll to .cpl. 4. To install the proxy linker, rename the original Visual Basic linker LinkLnk.exe, copy the proxy linker to the Visual Basic directory, and name it Link.exe. Once we create our proxy linker, we can reload our MathLib project and compile it into a DLL by selecting the Make MathLib.exe option from the File menu.
We can then use the following code in the form module to call the routines in the DLL:
Option Explicit Private Sub cmdDecrement_Click() txtDecrement.Text = Decrement(CInt(txtDecrement.Text)) End Sub Private Sub cmdIncrement_Click() txtIncrement.Text = Increment(CInt(txtIncrement.Text)) End Sub Private Sub cmdSquare_Click() txtSquare.Text = Square(CLng(txtSquare.Text)) End Sub Private Sub Form_Load()
When we call each of the MathLib functions, the application window might appear as it does in Figure 2, confirming that the calls to the MathLib routines work as expected.
Figure 2: Testing calls to MathLib.dll Ron Petrusha is the author and coauthor of many books, including "VBScript in a Nutshell." Return to the Windows DevCenter.
Co pyright 2009 O 'R e illy Media, Inc.