• vs2013 调用只有dll文件的动态库(一)


    有时候,用户只能得到dll动态库文件以及对这个文件的接口函数名称。当我们调用这个dll库时,我们就不能像平时一样,通过.lib,.h和.dll这三个文件来调用dll库内的算法了。

    这里介绍一种只提供dll函数接口与.dll文件的调用方法。

    顺带一下,先讲一下dll创建流程:

    创建--->项目--->Win32-->Win32控制应用程序--->DLL(D) 空项目

    添加头文件WinDll.h

    1 #ifndef LIB_H
    2 #define    LIB_H
    3 extern "C" int __declspec(dllexport) add(int x,int y);
    4 #endif

    注: 3 extern "C" int __declspec(dllexport) add(int x,int y); 申明动态库链接,这个很重要。

    添加WinDll.cpp源文件

    1 #include"Windll.h"
    2 int add(int x, int y)
    3 {
    4     return  x + y;
    5 }

    编译后,生成 WinDll.dll文件。至此,.dll文件创建完成。

    下面是如何调用这个dll文件。

    创建一个新的项目

    并创建添加源文件

     1 #include<stdio.h>
     2 #include<stdlib.h>
     3 #include<Windows.h>
     4 
     5 typedef int(*lpAddFun)(int, int);
     6 
     7 int main(int argc, char **argv)
     8 {
     9     HINSTANCE hDll;
    10     lpAddFun addFun;
    11     hDll = LoadLibrary(TEXT("..\WinDll.dll"));
    12     if (!hDll)
    13     {
    14         printf("Can't load dll.");
    15     }
    16     else
    17     {
    18         addFun = (lpAddFun)GetProcAddress(hDll, "add");
    19         if (addFun != NULL)
    20         {
    21             printf("result=%d
    ", addFun(1, 2));
    22         }
    23         FreeLibrary(hDll);
    24     }
    25     system("pause");
    26 }

    注: hDll = LoadLibrary(TEXT("..\WinDll.dll")); 加载dll文件,这个路径为dll存放路径,也就是我们要将之前生成的dll这个文件拷贝到当前项目目录下就可以了。

    编译运行:

    谢谢。

  • 相关阅读:
    300. Longest Increasing Subsequence_算法有误
    LIS (DP)_代码
    pthread_detach pthread_create实例
    pthread_detach
    DP(动态规划)
    括号匹配(二)
    gdb调试遇到的问题
    matplotlib 显示中文
    一个奇怪的编码 big5-hkscs
    python 重载 __hash__ __eq__
  • 原文地址:https://www.cnblogs.com/lumao1122-Milolu/p/11672333.html
Copyright © 2020-2023  润新知