Search code examples
c++dllboost-function

C++ Load function from DLL into Boost function


I want to load a particular function from DLL and store it inside the Boost function. Is this possible?

typedef void (*ProcFunc) (void);
typedef boost::function<void (void)> ProcFuncObj;
ACE_SHLIB_HANDLE file_handle = ACE_OS::dlopen("test.dll", 1);
ProcFunc func = (ProcFunc) ACE_OS::dlsym(file_handle, "func1");
ProcFuncObj fobj = func; //This compiles fine and executes fine
func(); //executes fine
fobj(); //but crashes when called

Thanks, Gokul.


Solution

  • You need to take care about names mangling and calling convention:

    So, in your DLL:

    // mydll.h
    #pragma comment(linker, "/EXPORT:fnmydll=_fnmydll@4") 
    extern "C" int WINAPI fnmydll(int value);
    
    // mydll.cpp
    #include "mydll.h"
    extern "C" int WINAPI fnmydll(int value)
    {
        return value;
    }
    

    Then, in your DLL client application:

    #include <windows.h>
    #include <boost/function.hpp>
    #include <iostream>
    
    int main()
    {
        HMODULE dll = ::LoadLibrary(L"mydll.dll");
        typedef int (WINAPI *fnmydll)(int);
    
        // example using conventional function pointer
        fnmydll f1 = (fnmydll)::GetProcAddress(dll, "fnmydll");
        std::cout << "fnmydll says: " << f1(3) << std::endl;
    
        // example using Boost.Function
        boost::function<int (int)> f2 = (fnmydll)::GetProcAddress(dll, "fnmydll");
        std::cout << "fnmydll says: " << f2(7) << std::endl;
        return 0;
    }
    

    I'm sure this example builds and runs well.