简体   繁体   中英

How to use DLL without header in C++

Help, please. A have a dll-file. I know it's functions and parameters. How can I use it in Eclipse with MinGW?

I am assuming you are using windows. In WINAPI you have LoadLibrary and GetProcAddress functions. Here's an example of usage

I understood you know the DLL function signature and you don't have the header.

For a given function dll_function with the known signature:

long dll_function(long, long, char*, char*);

You can use LoadLibrary and GetProcAddress from Windows API like examplified in the following C++ code:

#include <windows.h>
#include <iostream>

typedef long(__stdcall *f_funci)(long, long, char*, char*);


struct dll_func_args {
    long arg1;
    long arg2;
    std::string arg3;
    std::string arg4;
};

// Borrowing from https://stackoverflow.com/a/27296/832621
std::wstring s2ws(const std::string& s)
{
    int len;
    int slength = (int)s.length() + 1;
    len = MultiByteToWideChar(CP_ACP, 0, s.c_str(), slength, 0, 0);
    wchar_t* buf = new wchar_t[len];
    MultiByteToWideChar(CP_ACP, 0, s.c_str(), slength, buf, len);
    std::wstring r(buf);
    delete[] buf;
    return r;
}

int main()
{
    std::string filename = "C:\\...\\mydllfile.dll";
    dll_func_args args;
    args.arg1 = 1;
    args.arg2 = 2;
    args.arg3 = "arg3";
    args.arg4 = "arg4";

   std::wstring tmp = s2ws(filename);
    HINSTANCE hGetProcIDDLL = LoadLibrary(tmp.c_str());

    if (!hGetProcIDDLL)
    {
        std::cerr << "Failed to load DLL" << std::endl;
        return EXIT_FAILURE;
    }

    // resolve function address here
    dll_func_ptr func = (dll_func_ptr)GetProcAddress(hGetProcIDDLL, "dll_function");
    if (!func)
    {
        std::cout << "Failed to load function inside DLL" << std::endl;
        return EXIT_FAILURE;
    }

    std::cout << "Return value " << func(args.arg1, args.arg2, (char *)args.arg3.c_str(), (char *)args.arg4.c_str()) << std::endl;

    return EXIT_SUCCESS;
}

I created a wrapper to simplify this sort of thing a while back.

Update: I completely forgot about this post and deleted the blog post and associated source code. I wound up with a dangling pointer here ;-)

Luckily, someone did a much better job than I did: Boost.DLL

If you DO have appropriate .LIB file, and you have exact function prototype, you don't need header. Just declare the functions youself (possibly in your own custom header). Call those functions directly. Link with .LIB file. The DLL would get loaded by OS, and functions would be called.

If you don't have .LIB file to link to DLL, you need to use LoadLibrary and GetProcAddress as others have suggested.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM