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



我可以使用mingw正确编译DLL,并执行导出/导入操作。我正在寻找的是正确定义dll加载函数,就像你在微软VC产品中一样。谷歌什么也没发现。有人有什么想法或教程链接吗?

好吧,经过一番努力。。。它起作用了。对于其他有问题的人来说,这就是问题所在。我的问题与编译无关,而与动态加载无关。这是几个教程/问题/如何操作的结合,让我走到了这一步。

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 ("Hellon");
}

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...

由于mingw只是GCC和相关工具的窗口端口,因此可以使用GCC构造函数和析构函数属性。这些功能适用于共享库和静态库,并分别在main运行之前和之后执行代码。此外,您可以为每个库指定多个构造函数和析构函数。

static void __attribute__((constructor))
your_lib_init(void)
{
    fprintf(stderr, "library initn");
}
static void __attribute__((destructor))
your_lib_destroy(void)
{
    fprintf(stderr, "library destroyn");
}

最新更新