2013-03-08 66 views
1

任何人都可以告訴我我做錯了什麼嗎? 我想在另一個線程上運行一個自定義的主。讓DLL調用帶函數指針的exe函數

這是代碼。

.EXE
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功能?

+2

您的平臺構造函數尚未返回。在構造對象之前'main'不能運行,並且你的構造函數尚未完成。 – 2013-03-09 01:18:11

回答

1

C++標準不允許調用main()或取其地址,這就是您在這裏做的。請參閱this引用線條和詩句的線索。所以,你在做什麼是未定義的。