打开APP
userphoto
未登录

开通VIP,畅享免费电子书等14项超值服

开通VIP
Visual?Studio下建立并显示调用自己的动态链接库dll

Visual Studio下建立并显示调用自己的动态链接库dll

(2011-06-05 11:08:34)
分类: VS
在这篇文章中 http://blog.sina.com.cn/s/blog_6e0693f70100sn4a.html
作者简单讲述了如何生成并通过导出库和头文件隐式调用dll,下面作者将介绍一下如何显式调用dll。

在先前的例子中,__declspec(dllexport)表示这个函数是一个从DLL导出的函数。但在生成的dll中C++编译器将这个函数名做了很大的更改。使用dumpbin.exe可以查看dll里面的导出名。在先前的例子中,通过使用导出库和头文件,程序可以正常的隐式调用dll并加载这个函数。当我们需要显式调用dll时,这个被C++编译器更改过名字用起来很不方便。这时我们可以通过两种方法解决这个问题。

    方法一:在《VisualStudio下建立并隐式调用自己的动态链接库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 findZWang_library.dll!" << endl<< "Press any key to exit theprogram.";
      cin.get();
       return1;
    }
    else
    {
       pfp_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 theprogram.";
         cin.get();
         FreeLibrary(hdll);
         return 1;
       }
       else
       {
         (*p_call_from_dll)("Hello world!");
       }
    }
   FreeLibrary(hdll);
   cin.get();
    return0;
 
   
本站仅提供存储服务,所有内容均由用户发布,如发现有害或侵权内容,请点击举报
打开APP,阅读全文并永久保存 查看更多类似文章
猜你喜欢
类似文章
【热】打开小程序,算一算2024你的财运
Visual C++中调用DLL实现数据加密
将 动态链接库文件添加到VC程序中
DLL动态库的创建,隐式加载和显式加载
总结一下DLL函数声明的一些问题
使用c 开发excel插件 (3.4、编写一个简单的动态链接库)
Delphi中DLL的创建和使用
更多类似文章 >>
生活服务
热点新闻
分享 收藏 导长图 关注 下载文章
绑定账号成功
后续可登录账号畅享VIP特权!
如果VIP功能使用有故障,
可点击这里联系客服!

联系客服