首页 > 解决方案 > 从 C 中的 DLL 调用函数

问题描述

我已经阅读了 MSDN 文档,查看了其他示例,并且还向其他人寻求了帮助。到目前为止还没有人找到解决办法,所以 StackOverflow 是我最后的希望。

目前我的目标是从 DLL 调用一个函数。下面给出的示例使用MessageBox()位于user32.dll. 这在之前已经完成,但是当我尝试在 C 中执行此操作时,它会在调用GetProcAddress().

HMODULE hLib;
func_msgBox msgBox;
hLib = LoadLibrary("C:\\WINDOWS\\system32\\user32.dll");
if (hLib != NULL) {
    printf("[+] - Loaded our library");
    msgBox = (func_msgBox)GetProcAddress(hLib, "MessageBox");
    if (msgBox != NULL) {
        printf("[+] -  Recieved our process address");
        (func_msgBox)(NULL, "test", "test", 0);
        printf("[+] - Called our function");
    }
}
printf("Error: %s", GetLastError());
FreeLibrary(hLib);

标签: cwinapidllprocess

解决方案


如评论:

  1. 您需要明确指定MessageBox:MessageBoxAMessageBoxW.

  2. func_msgBox是一种函数指针,你需要使用实例msgBox来调用这个函数,如:

    msgBox(NULL, "test", "test", 0);

  3. 您需要将其编译为 64 位,因为您正在加载 64 位 DLL。

我可以重现崩溃,崩溃发生在printf,如果您指定名称"MessageBox"GetProcAddress失败并GetLastError返回 127(ERROR_PROC_NOT_FOUND),返回类型为DWORD,但您指定的格式为%s,通常需要字符串的地址。

以下示例适用于我:

#include <windows.h>
#include <stdio.h>

typedef int (WINAPI* func_msgBox)(
    HWND    hWnd,
    LPCSTR lpText,
    LPCSTR lpCaption,
    UINT    uType
);
void main(void)
{
    HMODULE hLib;
    func_msgBox msgBox;
    hLib = LoadLibraryA("C:\\WINDOWS\\system32\\user32.dll");
    if (hLib != NULL) {
        printf("[+] - Loaded our library");
        msgBox = (func_msgBox)GetProcAddress(hLib, "MessageBoxA");
        if (msgBox != NULL) {
            printf("[+] -  Recieved our process address");
            msgBox(NULL, "test", "test", 0);
            printf("[+] - Called our function");
        }
    }
    printf("Error: %d", GetLastError());
    FreeLibrary(hLib);
    return;
};

推荐阅读