让一个DLL调用带函数指针的exe函数 [英] letting a DLL call a exe function with function pointer
问题描述
任何人都可以告诉我我做错了什么?
我试图在不同的线程上运行自定义main。
Can anyone tell me what I'm doing wrong? I'm trying to run a custom main on a different thread.
这是代码。
.exe
main.cpp
.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
.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
platform.h
class DLL_API Platform
{
public:
Platform(main_t main_tp);
~Platform(void){}
};
platform.cpp
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);
}
它运行得很好,直到某一时刻。
这是输出。
It runs great, till a certain moment. This is the output.
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函数?
Is it impossible to let dll call a exe function?
推荐答案
从共享库调用可执行文件中的函数非常可能。但是,如另一个答案中提到的C标准不允许调用 main
。这与C运行时(以防止语言律师:插入有时在这里)依赖于一定的顺序的事实,如果你尝试调用 main
在C运行时完成正确的初始化之前, main
,你会遇到问题。
It is very much POSSIBLE to call a function in the executable file from a shared library. However, the C standard, as mentioned in the other answer, doesn't allow you to call main
. This has to do with the fact that the C runtime [to guard against language lawyers: insert "sometimes" here] relies on a certain order of things, and if you try to call main
before the C runtime has done the right initialization BEFORE main
, you get problems.
如果你的目标是实际上颠覆了 main
,那么你必须找到一种不同的方式这 - 至少如果你期望它工作于多个特定的可执行文件。
If your goal is to actually subvert what main
does, then you will have to find a different way of achieving this - at least if you expect it to work for more than one particular executable.
这篇关于让一个DLL调用带函数指针的exe函数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!