Using functions in a dll in c++?

637 Views Asked by At

I have created a dll in c++ using __declspec(dllexport) before class name. Now when i try to use it in another c++ program it crashes in between. When i debugged it i found that the function pointer is not initialized at all. help me plz.

using namespace std;

typedef void (*func)();

int main()

{

    func funcpointer;
    HINSTANCE xyz = LoadLibrary(TEXT("C:\\extra\\dll\\dlls\\debug\\random.dll"));
    funcpointer = (func)GetProcAddress(xyz,"get it");
    funcpointer();
    return 0;
}

Thanks in advance.

3

There are 3 best solutions below

2
Felice Pollano On BEST ANSWER

First of all use DUMPBIN /EXPORTS yourdll.dll to see if the function you expect to be exported is actually exported and its exact name. If you find the name "mangled" you probably need to declare the function as extern "C". Once you have determined the name the way you go is correct. Check also the HINSTANCE xyz became not null after loading the library. If null you robably don't reach the dll ( not in the search path ) or for some reason it can't load for example because some dependencies are missing.

0
Igor On
  1. Instead of "get it" you should write the name of the function you want to retrieve.
  2. You should have not only dllexport, but also the whole dllexport/dllimport definition in the retrieved function's header file:

    #if defined DLL_EXPORT   
    #define DECLDIR __declspec(dllexport)
    #else
    #define DECLDIR __declspec(dllimport)
    #endif
    
    extern "C"
    {
       DECLDIR void foo();
    }
    

You can read the DLL Tutorial for more details.

5
frast On

When you export your function use extern "C" fndecl. This will help to get an undecorated name or use a def-file. To check the name of the exported function use the tool Dependency Walker (depends.exe).

If you have a C++ class I would advise you to link to the DLL. Using GetProcAddress it would be a pain to use a C++ class.

This link could also be interesting for you if you are new to DLLs: Walkthrough: Creating and Using a Dynamic Link Library