Using dllimport with Visual C++

跟風遠走 提交于 2019-12-06 06:23:23

If you want to link DLL at runtime, you don't need to import symbols at all.

Just declare a function pointer type, then LoadLibrary()/LoadLibraryEx(), and finally retrieve function pointer from GetProcAddress().

Example (error handling is ommitted for brevity):

typedef int (*MyFunct_t)();
auto myDLL = LoadLibrary("mydll.dll");
auto MyFunct = (MyFunct_t)GetProcAddress(myDLL, "MyFunct");
MyFunct();

(this code is only to show general procedure, it was never compiled and tested and could contain typos and syntax errors, feel free to edit this post to fix them)

I did it this way:

1) Added a file MyLibDll.h to project

#pragma once

#if MYLIB_EXPORTS 
#define MYLIB_API __declspec(dllexport)
#else
#define MYLIB_API __declspec(dllimport)
#endif

2) Use this in library header files as

#include "MyLibDll.h"

    class MYLIB_API myClass
{

}

This can be used with methods to.

3) Added compiler option /D MYLIB_EXPORTS in .dll project.

Not sure if this is the best solution, but it worked for me.

__declspec(dllimport) tells the compiler that a symbol is imported, but it doesn't tell where from. To specify that, you need to link with the import library that accompanies the DLL. If you don't have one, you can have the linker generate it for you by providing a definition file.

You can use, dllimport like this,

extern "C"
{
__declspec(dllimport) int myFunct();
}

Just do remember myFunct should be dllexport from where you have defined it.

jww

I get 2 unresolved externals linker errors and a warning that /DELAYLOAD:myLib.dll...

This is a 3rd party DLL which comes without .h or .lib file.

Try adding the following to your source file:

#pragma comment(lib, "myLib")
extern int myFunct();

The pragma comment places an entry for the library in the object file. The second provides a declaration for the function.

From your comments, you might also be talking about /INCLUDE (Force Symbol References). You can place that in a source file with pragma comment, too.

If needed, you can create an import lib. See How To Create Import Libraries Without .OBJs or Source and How to generate an import library (LIB-file) from a DLL?.

Or, use LoadLibrary and GetrocAddress.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!