簡體   English   中英

如何為mingw32指定dll onload函數?

[英]How to specify dll onload function for mingw32?

我可以使用mingw正確編譯DLL並執行導出/導入操作。 我正在尋找的是正確定義dll onload功能,就像在MS 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 ("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_ */

你好ç


#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的Windows端口和相關工具,因此您可以使用GCC構造函數和析構函數屬性 這些工作分別用於共享庫和靜態庫,並分別在main運行之前和之后執行代碼。 此外,您可以為每個庫指定多個構造函數和析構函數。

static void __attribute__((constructor))
your_lib_init(void)
{
    fprintf(stderr, "library init\n");
}

static void __attribute__((destructor))
your_lib_destroy(void)
{
    fprintf(stderr, "library destroy\n");
}

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM