question

Thema-1898 avatar image
0 Votes"
Thema-1898 asked XiaopoYang-MSFT commented

Win32 Loading an Executable using LoadLibrary Crashes

Hi,

I am trying to load an executable (.exe) file called main2.exe into the address
space of another executable file. I used the Win32 LoadLibraryA function but
it only works when I convert main2.exe into a Dynamic Linked Library called
main2.dll.

Here is the code for main.c;

 #include <stdlib.h>
 #include <io.h>
 #include <windows.h>
    
 #define NULL 0
    
 DWORD function1(void *inobj);
    
 int main(int argc, char *argv[]){
    
  //Variable declarations.
  char *tmpstr = 0;
  HANDLE tmphnd = 0;
  HMODULE tmphnd2 = 0;
  int ret = 0;
    
  //Main logic.
    
  //Prepare variables.
  tmpstr = "main2.exe";
    
  tmphnd2 = LoadLibraryA(tmpstr);
  if(tmphnd2 == NULL){
   printf("\nLoadLibraryA failed.\n");
  }
    
  //Create and start a new thread.
  tmphnd = CreateThread(NULL, \
                NULL, \
                function1, \
                tmphnd2, \
                0, \
                NULL);
    
  //Let the main thread wait.
  system("pause");
    
 }
    
 DWORD function1(void *inobj){
    
  //Variable declarations.
  int (*tmpvoid)() = 0;
  char *tmpstr;
  HMODULE tmpvoid2 = 0;
    
  //Initializations.
  tmpvoid2 = (HMODULE)inobj;
    
  //Get the process address.
  tmpvoid = GetProcAddress(tmpvoid2, "PrintNumber");
    
  //Call the function of main2.exe.
  if(tmpvoid != NULL){
   tmpvoid();
  }
    
  //Free the library.
  FreeLibrary(tmpvoid2);
    
  //Returns.
  return 1;
    
 }

Here is the code for main2.c;

 #include <stdlib.h>
 #include <io.h>
 #include <windows.h>
    
 #define    DLLEXPORT __declspec(dllexport)
    
 int main(int argc, char *argv[]){
    
  printf("\nmain function entered.\n");
    
  system("pause");
    
 }
    
 DLLEXPORT int PrintNumber(){
    
  printf("\nThe number is 10.\n");
    
  return 10;
    
 }


windows-api
5 |1600 characters needed characters left characters exceeded

Up to 10 attachments (including images) can be used with a maximum of 3.0 MiB each and 30.0 MiB total.

1 Answer

RLWA32-6355 avatar image
1 Vote"
RLWA32-6355 answered XiaopoYang-MSFT commented

Yes, LoadLibrary can load an .exe but it doesn't mean that everything works the same as if it was a DLL. Read Darran Rowe's detailed explanations of why exporting functions from an .exe is problematic here -
exporting-functions-from-exe


· 1
5 |1600 characters needed characters left characters exceeded

Up to 10 attachments (including images) can be used with a maximum of 3.0 MiB each and 30.0 MiB total.

The Question has a sample Which also contains detailed explanations.


0 Votes 0 ·