Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
402 views
in Technique[技术] by (71.8m points)

c - LoadLibrary() an EXE?

I have an executable (that I created using Visual C++ 10), and I need to use its capabilities from another program I wrote (same environment). Due to complex deployment requirements which I won't go into, building a DLL from the required functionality and loading it in both programs is not something I can do.

So I thought that I can __declspec(dllexport) some functions in the EXE, and then LoadLibrary() will let me GetProcAddress() them.

Obviously this can't be done, though when I started looking at it - it looked feasible.

Specifically, when you __declspec(dllexport) functions in an EXE project, Visual C++ also generates a lib file for dynamic linking - so you don't even need to use LoadLibrary() - just link against the resulting lib and call the functions.

Unfortunately, the main problem is that when you declare the resulting file as an EXE, Visual C++ adds the "CRTmain" entry point into the resulting file, instead of the "CRTDLLmain" that a DLL gets. When Windows (automatically) LoadLibrary() the EXE from your main program, it doesn't call the the "CRTDLLmain" entry point (because it doesn't exist), the C runtime for the module doesn't get initialized, and as a result all interesting work (such as memory allocation) fails with interesting(*) runtime exceptions.

So as follows, my question is: is there a way to cause Visual C++ to build into the resulting file both the "CRTmain" entry point and the "CRTDLLmain" entry point?

(*) "Interesting" as in an old Chinese curse.

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

Yes it is possible.

http://www.codeproject.com/Articles/1045674/Load-EXE-as-DLL-Mission-Possible

The idea is a) to patch the IAT and b) to call the CRT before calling your exports.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...