簡體   English   中英

讓DLL用函數指針調用exe函數

[英]letting a DLL call a exe function with function pointer

誰能告訴我我做錯了什么? 我正在嘗試在不同的線程上運行自定義主程序。

這是代碼。

。可執行程序
main.cpp中

#include "dll_class.h"
#include <iostream>
int main(void);
DllClass object(main);
int main(void)
{
    std::cout << "Enter the main code.\n";
    std::getchar();
}

.DLL
dll_class.h

#include "platform.h"
#include <iostream>
class DLL_API DllClass //DLL_API is just a macro for import and export.
{
public:
    DllClass(int(*main)(void))
    {
        std::cout << "Start application.\n";
        platform = new Platform(main);
    }
    ~DllClass(void)
    {
        delete platform;
    }
private:
    Platform* platform;
};

platform.h

class DLL_API Platform
{
public:
    Platform(main_t main_tp);
    ~Platform(void){}
};

platform.cpp

#include "platform.h"
#include "Windows.h"
#include <iostream>

HHOOK hookHandle;
int(*main_p)(void);//This will hold a the main function of the the .exe.
LRESULT CALLBACK keyHandler(int nCode, WPARAM wParam, LPARAM lParam);

DWORD WINAPI callMain(_In_  LPVOID lpParameter)
{
    std::cout << "Calling the main function.\n";
    main_p();
    return 0;
}

Platform::Platform(int(*main_tp)(void))
{
    main_p = main_tp;
    CreateThread(NULL, 0, callMain, NULL, 0, NULL);
    std::cout << "Setting hooks.\n";
    hookHandle = SetWindowsHookEx(WH_MOUSE_LL, keyHandler, NULL, 0);
    std::cout << "Enter message loop.\n";
    MSG message;
    while(GetMessage(&message, (HWND)-1, 0, 0) != 0){
        TranslateMessage( &message );
        DispatchMessage( &message );
    }
}

LRESULT CALLBACK keyHandler(int nCode, WPARAM wParam, LPARAM lParam)
{
    std::cout << "Inside the hook function.\n" << std::endl;
    return CallNextHookEx(hookHandle, nCode, wParam, lParam);
}

它運行得很好,直到某個時刻。 這是輸出。

Start application.  
Setting hooks.  
Calling the main function.  
Enter message loop.  
Inside the hook function. (A lot of times of course).  

但它從未說過:

Enter the main code.

讓dll調用exe函數是不可能的嗎?

從共享庫調用可執行文件中的函數是非常可能的。 但是,如其他答案中所述,C標准不允許您調用main 這與以下事實有關:C運行時[防止語言律師:插入“有時”在這里]依賴於某種順序的東西,並且如果你嘗試在C運行時之前調用main ,那么在main運行之前進行正確的初始化,你會遇到問題。

如果您的目標是實際顛覆main功能,那么您將不得不找到一種不同的實現方式 - 至少如果您希望它可以用於多個特定的可執行文件。

C ++標准不允許調用main()或獲取其地址,這就是你在這里所做的。 請參閱引用行和詩句的主題。 那么,你所做的是未定義的。

暫無
暫無

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

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