-
help!! dll error
hi im developing a simple dll to learn win32 dll's, but when i run the test program an acess violation error is displayed by the operating system(windows xp), is not a compiler error because it compiles great,
here's the code
//dll header file dll2.h
Code:
//definicion de funciones y opciones para exportar las dll
#ifndef DLL2_H
#define DLL2_H
int number;
extern "C" int __stdcall square(int);
#endif
dll source code dllmain.cpp
Code:
#include "dll2.h"
int __stdcall square(int n)
{
number = n * n;
return number;
}
test program source test.cpp
Code:
#include <iostream>
using std::cout;
using std::endl;
#include <windows.h>
//pointer to function
typedef int(WINAPI* ptrFunc)(int);
int main(int argc, char *argv[])
{
HINSTANCE dllLib= 0;
ptrFunc funcion1 = 0;
dllLib = LoadLibrary("DLL2.DLL");
if(!dllLib){
cout << "No se pudo cargar DLL!" << endl;
return 0;
}
funcion1 = (ptrFunc)GetProcAddress(dllLib,"square");
//displays the square of 2
cout << funcion1(2) << endl;
FreeLibrary(dllLib);
return 0;
}
as i said above the program compiles just rigth but when i run it i have a memory error or something like that
if my function do not returns a value the program runs fine, i think the problem is when a function returns something from a dll function
any idea?
thanks for any help
and please excuse my poor english
-
The reason you are getting the run-time error is that GetProcAddress is failing and returning 0. Therefore you get the error when you try to call function1(). You need to check the return value of GetProcAddress before you try to call the function.
Now the reason GetProcAddress is failing is probably because you are not exporting the function from the DLL (unless you are using a .def file).
Try changing your function to:
Code:
extern "C" int __declspec(dllexport) __stdcall square(int);
-
i changed that and still the same problem, this dll's are driving me crazy
thanks for reply
-
Why can't I GetProcAddress a function I dllexport'ed?
You could create a .def file or use:
Code:
funcion1 = (ptrFunc)GetProcAddress(dllLib,"_square@4");
-
ok, i already created a .def file and now my program runs fine :-)
more people use .def files or exports the dll functions from a normal .h file withe the "extern C...." func(...) ?
in other words is better to use a def file than "the other" method?
thanks for your help
-
def files make it a little easier since you dont have to worry about name decorations when you are writing the code which calls the DLL functions.
When creating dlls, most people actually create a library file to go along with the dll to make using the dll functions even easier. There are tools (I cant think of their names off hand) to create a .lib file from a dll file. Then to use that dll file, you just have to include the dll header, and link to the library file. Then you can call the functions like normal. If you are using the microsoft C++ compiler, then a .lib file is created automatically when you create a .dll file.
-