让dll通过发送一个指针来调用.exe函数

Let a dll call a .exe function by sending a pointer

本文关键字:指针 一个 调用 函数 exe dll      更新时间:2023-10-16

这个问题看起来像我以前问过的问题,除了我现在知道不能从全局对象调用main函数。所以这段代码对main不起作用。但是为什么它在其他函数中也会失败呢?

这是代码。

. exe
main.cpp

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

.
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 my_main code.
Enter the main code.

是不可能让dll调用exe函数?

答案仍然是一样的,我给你的另一个问题。你的Platform构造函数挂起了。循环终止条件永远不会满足,因此构造函数永远不会返回。main函数不能运行,直到所有全局对象都被构造好。

更新:上面的讨论是为什么Enter the main code从不打印。

如果您逐步执行my_main函数,您将看到Enter the my_main code的问题:对coutgetchar的调用被忽略。这是因为在不同的翻译单元中,全局对象的构造顺序是未指定的。在主可执行程序中,object全局对象首先被构造,这意味着cincout对象可能没有被完全构造。这就是cout不能打印,getchar不能读取的原因。

当然,正确的做法是在main内部构造object。如果需要,将my_main传递给对象。但这将解决所有"试图在构建之前使用某些东西"的问题。

这里的关键(我只从阅读其他答案的评论中收集)是cout对象不是主可执行文件和DLL的"同一对象"。这导致在进入main之前调用cout的事情的问题[我也试图在上一个问题中解释- C运行时库需要初始化某些东西,并且在main调用之前以未指定的顺序发生]。