65.9K
CodeProject 正在变化。 阅读更多。
Home

MASM 创建 DLL 简介

starIconstarIconstarIconstarIcon
emptyStarIcon
starIcon

4.14/5 (5投票s)

2009年10月4日

CPOL

2分钟阅读

viewsIcon

40906

downloadIcon

1555

展示了如何创建一个简单的 DLL 并在另一个程序中调用它

引言

在本文中,我将讨论使用汇编语言 (MASM) 创建 DLL,以及创建调用该示例 DLL 的程序。

DLL 的创建

步骤

首先,你需要做一些事情。定义常规内容(.386 和 include 文件),然后你需要声明 DLL 的主过程(LibMain),接下来是 DLL 的所有其他过程。在本教程中,我将只使用一个(PrintMess),但你可以根据需要使用任意数量的过程。

这是示例 DLL 的代码

 .386
option casemap :none   ; case sensitive
 include \masm32\include\masm32rt.inc 
.code
LibMain proc instance:dword,reason:dword,unused:dword 
    mov     eax,1
    ret
LibMain     endp
PrintMess proc
    print "Test", 10   ; message that will be printed by another program
    inkey   ; like pause command in batch
    exit   ; exits the program
PrintMess endp
End LibMain

简要描述

PrintMess 过程中,我使用 print 在屏幕上显示一条消息,然后 10 行后将光标移动到新行,以便 inkey 函数工作。现在让我们转到将使用此 DLL 的程序。

程序的创建

步骤

首先,你需要做一些事情。定义常规内容(.386.model 和 include 文件),然后你将声明一些变量(hLibhProc),接下来是使用 DLL 的 main 程序。

这是示例程序的代码

.386
.model stdcall,flat
 include \masm32\include\kernel32.inc
 includelib \masm32\lib\kernel32.lib
 
.data
    hLib dword ?
    hProc dword ?
.data
    lib byte "testdll.dll", 0
    function byte "PrintMess", 0
.code
start:
    push offset lib
    call LoadLibrary ; will load the dll
    mov hLib, eax
    push offset function
    push hLib
    call GetProcAddress ; will get the procedure to execute
    mov hProc, eax
    call hProc ; will call your function in your DLL
    push hLib
    call FreeLibrary ; free the resource
    ret
end start

简要描述

现在让我们快速解释一下代码。我声明了一个名为 lib 的变量,它将存储 DLL 的位置以打开它,以及另一个名为 function 的变量,它将存储程序将要执行的过程(请记住,你可以为其他过程创建许多其他变量),然后程序将使用 LoadLibrary 加载 DLL,该 DLL 存储在 hLib 变量中。接下来,GetProcAddress 将获取过程的地址(PrintMess)。之后,我们需要调用 hProc 中的函数,并最终需要使用 FreeLibrary 函数释放 DLL。

历史

  • 2009年10月4日:初始发布
© . All rights reserved.