Calling functions in a DLL from C++

117,846

Solution 1

There are many ways to do this but I think one of the easiest options is to link the application to the DLL at link time and then use a definition file to define the symbols to be exported from the DLL.

CAVEAT: The definition file approach works bests for undecorated symbol names. If you want to export decorated symbols then it is probably better to NOT USE the definition file approach.

Here is an simple example on how this is done.

Step 1: Define the function in the export.h file.

int WINAPI IsolatedFunction(const char *title, const char *test);

Step 2: Define the function in the export.cpp file.

#include <windows.h>

int WINAPI IsolatedFunction(const char *title, const char *test)
{
    MessageBox(0, title, test, MB_OK);
    return 1;
}

Step 3: Define the function as an export in the export.def defintion file.

EXPORTS    IsolatedFunction          @1

Step 4: Create a DLL project and add the export.cpp and export.def files to this project. Building this project will create an export.dll and an export.lib file.

The following two steps link to the DLL at link time. If you don't want to define the entry points at link time, ignore the next two steps and use the LoadLibrary and GetProcAddress to load the function entry point at runtime.

Step 5: Create a Test application project to use the dll by adding the export.lib file to the project. Copy the export.dll file to ths same location as the Test console executable.

Step 6: Call the IsolatedFunction function from within the Test application as shown below.

#include "stdafx.h"

// get the function prototype of the imported function
#include "../export/export.h"

int APIENTRY WinMain(HINSTANCE hInstance,
                     HINSTANCE hPrevInstance,
                     LPSTR     lpCmdLine,
                     int       nCmdShow)
{
    // call the imported function found in the dll
    int result = IsolatedFunction("hello", "world");

    return 0;
}

Solution 2

Can also export functions from dll and import from the exe, it is more tricky at first but in the end is much easier than calling LoadLibrary/GetProcAddress. See MSDN.

When creating the project with the VS wizard there's a check box in the dll that let you export functions.

Then, in the exe application you only have to #include a header from the dll with the proper definitions, and add the dll project as a dependency to the exe application.

Check this other question if you want to investigate this point further Exporting functions from a DLL with dllexport.

Solution 3

The following are the 5 steps required:

  1. declare the function pointer
  2. Load the library
  3. Get the procedure address
  4. assign it to function pointer
  5. call the function using function pointer

You can find the step by step VC++ IDE screen shot at http://www.softwareandfinance.com/Visual_CPP/DLLDynamicBinding.html

Here is the code snippet:

int main()
{
/***
__declspec(dllimport) bool GetWelcomeMessage(char *buf, int len); // used for static binding
 ***/
    typedef bool (*GW)(char *buf, int len);

    HMODULE hModule = LoadLibrary(TEXT("TestServer.DLL"));
    GW GetWelcomeMessage = (GW) GetProcAddress(hModule, "GetWelcomeMessage");

    char buf[128];
    if(GetWelcomeMessage(buf, 128) == true)
        std::cout << buf;
        return 0;
}

Solution 4

You can either go the LoadLibrary/GetProcAddress route (as Harper mentioned in his answer, here's link to the run-time dynamic linking MSDN sample again) or you can link your console application to the .lib produced from the DLL project and include the hea.h file with the declaration of your function (as described in the load-time dynamic linking MSDN sample)

In both cases, you need to make sure your DLL exports the function you want to call properly. The easiest way to do it is by using __declspec(dllexport) on the function declaration (as shown in the creating a simple dynamic-link library MSDN sample), though you can do it also through the corresponding .def file in your DLL project.

For more information on the topic of DLLs, you should browse through the MSDN About Dynamic-Link Libraries topic.

Solution 5

Might be useful: https://www.codeproject.com/Articles/6299/Step-by-Step-Calling-C-DLLs-from-VC-and-VB-Part-4

For the example above with "GetWelcomeMessage" you might need to specify "__stdcall" in the typedef field before the function name if getting error after calling imported function.

Share:
117,846
QueueHammer
Author by

QueueHammer

Software Developer, Runner, Pragmatist. Web Page: http://cmsmith.co Twitter: https://twitter.com/cmsmithco

Updated on September 11, 2020

Comments

  • QueueHammer
    QueueHammer over 3 years

    I have a solution in VS 2008 with 2 projects in it. One is a DLL written in C++ and the other is a simple C++ console application created from a blank project. I would like know how to call the functions in the DLL from the application.

    Assume I am starting with a blank C++ project and that I want to call a function called int IsolatedFunction(int someParam)

    How do I call it?

  • V-SHY
    V-SHY over 9 years
    beside of add the export.def files to this project, I need to point to the .def file in Linker -> Input -> Module Definition File such as $(SolutionDir)export.def
  • V-SHY
    V-SHY over 9 years
    You need #include <windows.h> for step 6 also.
  • jussij
    jussij over 9 years
    You are correct that the windows.h is needed. In the example above the I was using the #include "stdafx.h" file which is the precompiled header file. In this case that file contained the windows.h include.
  • V-SHY
    V-SHY over 9 years
    yes, you are right, I created Win32 console application and that why my one don't have and you created Win32 Project so you have it inside stdafx.h. Just know the difference.thanks
  • James Joshua Street
    James Joshua Street about 9 years
    so does the .lib file therefore contain the .h file interface created earlier? I came across this article trying to figure out why something i had wouldn't compile. I was wondering if failure to find the .h file when building a program that uses an external library would imply that the .lib file for the dll is not being found correctly.
  • veight
    veight about 9 years
    James Joshua Street wrote: so does the .lib file therefore contain the .h file interface created earlier? No.The .h file is used by the compiler. The .lib file is used by the linker.