zoukankan      html  css  js  c++  java
  • dll 文件创建与使用

          动态链接库(dll)文件主要用来共享程序,节省计算机运行时的内存空间。创建和使用dll文件一般都有两种方式(具体自己搜搜看)。这里说说我使用创建和调用方式。

    dll 文件的创建:

          创建工具可以使用vc6.0即可,当然visual studio 更好。

          dll 中包含的是一组函数(对于c++来讲,面向对象这种方式在这里几乎派不上用场),是一个函数库。这里创建时有3个文件,.h,.cpp和 .def 文件。.h 和 .cpp 文件就是普通的头文件和源文件。

    int sum(int arg1, int arg2);
    
    int sub(int arg1, int arg2);
    
    int big(int arg1, int arg2);
    int sum(int arg1, int arg2)
    {
        return arg1 + arg2;
    }
    
    int sub(int arg1, int arg2)
    {
        return arg1 - arg2;
    }
    
    int big(int arg1, int arg2)
    {
        return arg1 > arg2 ? arg1 : arg2;
    }

    上面简单的写了头文件和源文件。现在看下 def 文件。

    ;def example
    LIBRARY insyeah_math_dll.dll EXPORTS sum @
    1 sub @2 big @3

    def 文件指定了dll库名和要导出的函数名,@1,@2指明函数顺序。完成三个文件之后便可编译成链接库文件。有用的是 .h,.lib 和 .dll 文件。但是,为了减少调用时的麻烦步骤,只要.dll文件即可。

    dll 文件的使用:

          一个dll 文件是一个函数库,调用时只要指定库和库中的函数即可。如下面的调用:

    #include <windows.h>
    #include <iostream>
    
    using namespace std;
    
    typedef int (*MathDLL)(int, int);
    
    int main()
    {
        MathDLL math;
    
        //load math dll
        HMODULE hModule = ::LoadLibrary(TEXT("insyeah_math_dll.dll"));
    
        if(hModule == NULL)
        {
            ::FreeLibrary(hModule);
        }
    
        math = (MathDLL)::GetProcAddress(hModule, "sum");
        if(math == NULL)
        {
            ::FreeLibrary(hModule);
        }
    
        int res = math(5, 5);
    
        cout << res << endl;
    
        ::FreeLibrary(hModule);
    
        system("PAUSE");
        return 0;
    
    }

    上面的 LoadLibrary 指明调用的库名,GetProcAddress 指明库中的函数名。 FreeLibraray 关闭库调用。调用过程比较简单,只是在调用的时候需要设置与库中函数相应的函数指针,再根据指针调用函数。

  • 相关阅读:
    POJ 题目1145/UVA题目112 Tree Summing(二叉树遍历)
    车牌号
    小程序开发 标题新闻
    小程序开发 轮播
    小程序开发
    App phonegap
    Jquery Cookie操作
    App 添加权限
    App WebView实例化
    Vue 组件化
  • 原文地址:https://www.cnblogs.com/rereadyou/p/2836649.html
Copyright © 2011-2022 走看看