Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

__declspec(dllimport) how to load library

Tags:

c++

dll

dllexport

http://msdn.microsoft.com/en-us/library/9h658af8.aspx

MSDN says I can export function from the library with __declspec(dllexport) but how can I load this library in my executable?

I've got an exported function in DLL:

 __declspec(dllexport) void myfunc(){}

And now I would like to use it in my executable:

 __declspec(dllimport) void myfunc(void);

But how my program will know where to find this function?

like image 678
deepspace Avatar asked Jul 29 '13 22:07

deepspace


People also ask

What does __ Declspec Dllimport mean?

__declspec(dllimport) is a storage-class specifier that tells the compiler that a function or object or data type is defined in an external DLL. The function or object or data type is exported from a DLL with a corresponding __declspec(dllexport) .

Is __ Declspec Dllimport necessary?

Using __declspec(dllimport) is optional on function declarations, but the compiler produces more efficient code if you use this keyword. However, you must use __declspec(dllimport) for the importing executable to access the DLL's public data symbols and objects.

What is __ Declspec in C++?

The extended attribute syntax for specifying storage-class information uses the __declspec keyword, which specifies that an instance of a given type is to be stored with a Microsoft-specific storage-class attribute listed below. Examples of other storage-class modifiers include the static and extern keywords.


2 Answers

If you are using a DLL, you can to use the LoadLibrary and GetProcAddress combination.

//Load the DLL
HMODULE lib = LoadLibrary("testing.dll");

//Create the function
typedef void (*FNPTR)();
FNPTR myfunc = (FNPTR)GetProcAddress(lib, "myfunc");

//EDIT: For additional safety, check to see if it loaded
if (!myfunc) {
    //ERROR.  Handle it.
}

//Call it!
myfunc();
like image 61
Kirk Backus Avatar answered Sep 22 '22 14:09

Kirk Backus


This is the compiler/linker job, it's done automatically as long as you

  1. include the .lib in the Linker options
  2. provide the DLL at runtime so that it's found by the exe

The .lib file is generated when you compile the DLL, or is shipped with it if it's not your code. In this case the code is compiled with __declspec(dllexport).

When compiling your exe, the compiler sees that the included function is to be found in DLL. In this case the code is compiled with __declspec(dllimport).

The linker is provided with the .lib file, and generates appropriate instructions in the exe.

These instructions will make the Exe find the DLL and load the exported function at runtime. The DLL just has to be next to the Exe (there are other possible places, however).

Switching between __declspec(dllimport) and __declspec(dllexport) is done by a macro, provided by Visual C++ when creating a DLL project.

like image 36
CharlesB Avatar answered Sep 20 '22 14:09

CharlesB