C ++ / CLI: use LoadLibrary + GetProcAddress with exe

So far, I had some kind of plugin mechanism in which I loaded the dll using LoadLibrary and GetProcAddress to create a specific object and return a common interface. This worked fine until I decided that one of the libraries should be exe.

The LoadLibrary documentation says that it can be used for exe too, so I gave it a chance. Exe loads without errors, like GetProcAddress. But when I try to call my constructor for specific objects, I get an access violation.

I thought this would happen because exe loading does not load all the dlls that it uses. So I tried loading them using LoadLibrary, but I got the same error. Any advice on this?

Here is my code (mixed C ++ / CLI):

Interface* MCFactory::LoadInstanceFromAssembly( String ^ concreteAssemblyName, String ^ param ){ string fullPathToAssembly = ""; fullPathToAssembly += FileSystem::GetPathToProgramDirectory(); fullPathToAssembly += "\\" + marshal_as<string>(concreteAssemblyName); MODULE hDLL = AssemblyLoader::GetInstance().LoadAssembly( fullPathToAssembly ); Interface* pObject = NULL; if (hDLL != NULL){ t_pCreateInstanceFunction pCreateInstanceFunction = (t_pCreateInstanceFunction) ::GetProcAddress (hDLL, CREATE_INSTANCE_FUNCTION_NAME.c_str()); if ( pCreateInstanceFunction != NULL ){ //Yes, this assembly exposes the function we need //Invoke the function to create the object pObject = (*pCreateInstanceFunction)( marshal_as<string>(param) ); } } return pObject; } 

(AssemblyLoader :: GetInstance (). LoadAssembly is just a wrapper for :: LoadLibrary)

+4
source share
3 answers

Maybe.

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

The idea is to fix the IAT and then call the CRT. Of course, EXE must be roaming and default (ASLR).

+2
source

You can use LoadLibrary and GetProcAddress in the main executable file for your process, this allows dynamic export in the opposite direction (.exe to .dll).

You cannot load the second .exe into the process memory space, except for access to resources / data, because the .exe code does not move. (Pure MSIL.exe files are an exception because there is no code in the file; all this is generated by JIT.)

Basically, LoadLibrary in .exe is only useful when

  • .exe is the main exe process, in which case you can use GetModuleHandle

    or

  • The flag LOAD_LIBRARY_AS_DATAFILE

+6
source

While Ben's answer covers most cases, this article http://sandsprite.com/CodeStuff/Using_an_exe_as_a_dll.html may be useful in some circumstances.

+2
source

All Articles