Win32 Loading an Executable using LoadLibrary Crashes

Thema 21 Reputation points
2021-07-18T11:41:50.46+00:00

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 development | Windows API - Win32
0 comments No comments
{count} votes

1 answer

Sort by: Most helpful
  1. RLWA32 49,551 Reputation points
    2021-07-18T12:18:29.963+00:00

    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 person found this answer helpful.

Your answer

Answers can be marked as Accepted Answers by the question author, which helps users to know the answer solved the author's problem.