在这篇文章中 http://blog.sina.com.cn/s/blog_6e0693f70100sn4a.html
作者简单讲述了如何生成并通过导出库和头文件隐式调用dll,下面作者将介绍一下如何显式调用dll。
在先前的例子中,
__declspec(dllexport)表示这个函数是一个从DLL导出的函数。但在生成的dll中C++编译器将这个函数名做了很大的更改。使用dumpbin.exe可以查看dll里面的导出名。在先前的例子中,通过使用导出库和头文件,程序可以正常的隐式调用dll并加载这个函数。当我们需要显式调用dll时,这个被C++编译器更改过名字用起来很不方便。这时我们可以通过两种方法解决这个问题。
方法一:在《Visual
Studio下建立并隐式调用自己的动态链接库dll》一文的步骤3中,将
__declspec(dllexport) void call_from_dll(const string
&str = "Call the funtion from dll.");
改为
extern "C"
__declspec(dllexport) void call_from_dll(const string
&str = "Call the funtion from dll.");
这里extern
"C"表示用C语言方式编译和连接的call_from_dll函数,这样dll中的名字还是call_from_dll。
方法二:我们可以在《Visual Studio下建立并隐式调用自己的动态链接库dll》一文的步骤3中后增添如下更改。
1).
打开project -> ZWang_library properties
-> Linker -> Input ->
Module Definition File中添加 .\ZWang_library.def。
2).
通过Project -> Add New Item -> Code
-> Module-Definition File
添加一个名为ZWang_library.def的def文件。内容如下:
LIBRARY
"ZWang_library"
EXPORTS
call_from_dll
3).
编译ZWang_calldl,生成ZWang_library.dll放到包含ZWang_calldll.exe的文件夹中。运行程序。
这里我们通过一个Win32 Console Application来显示调用动态链接库dll,cpp文件代码如下
#include "stdafx.h"
#include <iostream>
#include <windows.h>
using namespace std;
int _tmain(int argc, _TCHAR* argv[])
{
typedef void
(*pf) (const string &str);
HMODULE hdll
= ::LoadLibrary("ZWang_library.dll");
if ( NULL ==
hdll )
{
cerr
<< "Error! Can't find
ZWang_library.dll!" << endl
<< "Press any key to exit the
program.";
cin.get();
return
1;
}
else
{
pf
p_call_from_dll = (pf)GetProcAddress( hdll,"call_from_dll" );
if (NULL ==
p_call_from_dll)
{
cerr << "Error!
Can't find call_from_dll function!"
<< endl
<< "Press any key to exit the
program.";
cin.get();
FreeLibrary(hdll);
return 1;
}
else
{
(*p_call_from_dll)("Hello world!");
}
}
FreeLibrary(hdll);
cin.get();
return
0;
}