Creating a Windows DLL with Visual Basic by Ron Petrusha 04/26/2005 As the first rapid application development language, Visual Basic attracted attention for its elegant graphical interface and overall ease of use, which allowed a relatively inexperienced programmer to accomplish in minutes what often took days for advanced programmers using languages like C and C++. As a result, Visual Basic drew millions of new programmers, many of whom might never have even considered programming had it not been for the language's simplicity. Because of this simplicity, and because Visual Basic was attracting a following that the proponents of other languages could only dream of, non-Visual Basic programmers (who were really green with envy) counterattacked by pointing to the inexperience of most Visual Basic programmers and to the problems that stem from Visual Basic's design goal of shielding the developer from the complexities of the underlying operating system. To bolster their contention that Visual Basic is underpowered and underdeveloped, critics liked to point to the many things "real" programmers do that Visual Basic programmers cannot. Perhaps the most common limitation that critics continually point to is Visual Basic's inability to create a standard Windows dynamic link library (DLL). Certainly it's true that out of the box, Visual Basic doesn't allow you to create a Windows DLL in the same way that you can create other project types, like a Standard EXE or an ActiveX DLL. In this article, we'll go exploring to see how Visual Basic generates its executables. In the process, we'll discover that with a little bit of extra work, we can in fact create Windows DLLs with Visual Basic. What Is a Windows Dynamic Link Library? A dynamic link library (DLL) is a library of functions and procedures that can be called from an application or another DLL. Using a library in this way has two major functions: It permits the sharing of code. The same DLL can be used by many other DLLs and applications. The Win32 API, for instance, is implemented as a series of Windows DLLs. Moreover, as long as multiple processes load the same DLL at the same base address, they can share the code in the DLL. In other words, a single DLL in memory can be accessed by multiple processes. It allows for component-based and modular development, which makes development and the upgrade process easier. Ordinarily, when a static library is used in application development, the library's modules must be linked into the finished application. With dynamic linking, the modules reside in a separate DLL file that is loaded dynamically, either when the application loads or when its member functions are needed. 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 Its parameters are: hInstDLL, a Long containing the instance handle of the DLL. This is the same as the DLL's module handle. fdwReason, a constant indicating why the entry point has been called. Possible values are: DLL_PROCESS_ATTACH (1) A process is loading the DLL. Any per-process initialization should be performed. DLL_THREAD_ATTACH (2) The process is spawning a new thread. Any per-thread initialization should be performed. DLL_THREAD_DETACH (3) A thread is exiting. Any per-thread cleanup should be performed. DLL_PROCESS_DETACH (0) 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 Code In attempting to develop a Windows DLL, we'll create a very simple library of math functions. The following is the DLL's code, which we'll store in a code module (a .bas file) named MathLib: Option Explicit Public Const DLL_PROCESS_DETACH = 0 Public Const DLL_PROCESS_ATTACH = 1 Public Const DLL_THREAD_ATTACH = 2 Public Const 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
Creating a Windows DLL with Visual Basic
最新推荐文章于 2021-03-26 03:20:53 发布