c - 如何为mingw32指定dll onload函数?

标签 c dll mingw onload mingw32

我可以使用 mingw 正确编译 DLL 并执行导出/导入操作。我正在寻找的是像在 MS VC 产品中那样正确定义 dll onload 函数。谷歌没有发现任何东西。任何人有任何想法或教程链接?

最佳答案

好吧,经过一些摆弄……它开始工作了。对于这里有问题的任何其他人来说。我的问题与编译而不是动态加载无关。这是几个教程/问题/操作方法的混搭,让我走到了这一步。

dll.c


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

//extern "C" BOOL WINAPI DllMain(HINSTANCE hinstDLL, DWORD Reason, LPVOID LPV) {
//This one was only necessary if you were using a C++ compiler

BOOL WINAPI DllMain(HINSTANCE hinstDLL, DWORD fdwReason, LPVOID lpvReserved) {

    switch (fdwReason)
    {
        case DLL_PROCESS_ATTACH:
            // Code to run when the DLL is loaded
        printf ("Load working...\n");
            break;

        case DLL_PROCESS_DETACH:
            // Code to run when the DLL is freed
        printf ("Unload working...\n");
            break;

        case DLL_THREAD_ATTACH:
            // Code to run when a thread is created during the DLL's lifetime
        printf ("ThreadLoad working...\n");
            break;

        case DLL_THREAD_DETACH:
            // Code to run when a thread ends normally.
        printf ("ThreadUnload working...\n");
            break;
    }

    return TRUE;
} 

EXPORT void hello(void) {
    printf ("Hello\n");
}

dll.h


#ifndef DLL_H_
#define DLL_H_

#ifdef BUILD_DLL
/* DLL export */
#define EXPORT __declspec(dllexport)
#else
/* EXE import */
#define EXPORT __declspec(dllimport)
#endif

EXPORT void hello(void);

#endif /* DLL_H_ */

你好.c


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

int main () {

    /*Typedef the hello function*/
    typedef void (*pfunc)();

    /*Windows handle*/
    HANDLE hdll;

    /*A pointer to a function*/
    pfunc hello;

    /*LoadLibrary*/
    hdll = LoadLibrary("message.dll");

    /*GetProcAddress*/
    hello = (pfunc)GetProcAddress(hdll, "hello");

    /*Call the function*/
    hello();
    return 0;
}

编译时

gcc -c -DBUILD_DLL dll.c
gcc -shared -o message.dll dll.o -Wl,--out-implib,libmessage.a
gcc -c hello.c
gcc -o hello.exe hello.o message.dll

产生预期的输出

Load working...
Hello
Unload working...

关于c - 如何为mingw32指定dll onload函数?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/6431345/

相关文章:

c - 尝试用 C 创建基本的二叉搜索树,但对 'unused variable' 感到困惑?

c - 为什么在尝试为原始指针值赋予新值时会导致错误?

c++ - 如果没有管理员权限,我应该把 freeglut.dll 放在哪里?

c++ - 在 C++ 中,程序不会永远停止

c - 使用 IShellLink 将我的可执行文件膨胀到 20KB

c - libc.so 在一个进程中映射了四个段,为什么?

c - 将无穷大赋给 float

c - 需要 MSVCR120.DLL

Windows 中的 C 标准库链接

c - 变量多重定义警告