Reputation: 501
I'm trying to dynamically load a dll
and call a function from it at runtime. I have succeeded in getting a working pointer with GetProcAddress
, but the program crashes if the function from the dll
uses the stdlib
. Here's the code from the executable that loads the dll
:
#include <iostream>
#include <windows.h>
typedef int (*myFunc_t)(int);
int main(void) {
using namespace std;
HINSTANCE dll = LoadLibrary("demo.dll");
if (!dll) {
cerr << "Could not load dll 'demo.dll'" << endl;
return 1;
}
myFunc_t myFunc = (myFunc_t) GetProcAddress(dll, "myFunc");
if (!myFunc) {
FreeLibrary(dll);
cerr << "Could not find function 'myFunc'" << endl;
return 1;
}
cout << "Successfully loaded myFunc!" << endl;
cout << myFunc(3) << endl;
cout << myFunc(7) << endl;
cout << myFunc(42) << endl;
cout << "Successfully called myFunc!" << endl;
FreeLibrary(dll);
return 0;
}
Here's code for the dll
that actually works:
#include <iostream>
extern "C" {
__declspec(dllexport) int myFunc(int demo) {
//std::cout << "myFunc(" << demo << ")" << std::endl;
return demo * demo;
}
}
int main(void) {
return 0;
}
(Note that the main
method in the dll
code is just to appease the compiler)
If I uncomment the line with std::cout
however, then the program crashes after the cout << "Sucessfully loaded myFunc!" << endl;
line but before anything else gets printed. I know there must be some way to do what I want; what do I need to change for it to work?
Upvotes: 1
Views: 639
Reputation: 501
As discussed in the comments, it turns out that the compiler's demands for a main
function were hints that I was inadvertently making a an exe
that decptively used the file extension dll
, not an actual dll
(because I didn't quite understand the compiler options I was using), which in some way messed up the dynamic loading of that assembly.
Upvotes: 1