如何在另一个项目的dll中添加调用函数

时间:2011-03-14 16:29:45

标签: c++ visual-studio

我有一个控制台C ++应用程序,我想在另一个DLL C ++项目中调用函数add()。这样做的方法是什么?

2 个答案:

答案 0 :(得分:5)

使用LoadLibrary然后GetProcAddress获取函数指针。

答案 1 :(得分:0)

DLL文件可以通过项目中包含的相应.LIB文件及其标题#include "MyUtils.h"来访问。这就是所谓的静态链接,就你所关注的而言,它都是在编译时完成的,你调用DLL的函数就好像它们是在你自己的应用程序中定义的一样。

另一种方法是动态链接,其中您实际加载DLL并在进行调用之前获取函数的地址。这种方法的一个例子如下:

// Declare the 'type' of the function, for easier use.
typedef BOOL (* t_MyFunc)(DWORD dwParam1, int nParam2);

// Declare a pointer to the function. Via this pointer we'll make the call.
t_MyFunc MyFunc     = 0;
BOOL bResult    = FALSE;

// Load the DLL.
HMODULE hModule = LoadLibrary("MyDLL.dll");
assert(hModule);
// Obtain the function's address.
MyFunc = (t_MyFunc)GetProcAddress(hModule, "MyDLL.dll");
assert(MyFunc);

// Use the function.
bResult = MyFunc(0xFF00, 2);

// No need in MyDll.dll or MyFunc anymore. Free the resources.
FreeLibrary(hModule);

还需要考虑几个因素,具体取决于您是编译DLL还是使用其他函数,例如函数的导出方式。但这应该让你开始。

相关问题