Visual C++ DLL的显式链接示例

一、DLL部分:

    1、dlldemo.h

         extern "C" _declspec(dllexport) int Sum(int a,int b);   //加法函数。
         extern "C" _declspec(dllexport) int Max(int a, int b);   //取较大值函数
         extern "C" _declspec(dllexport) int Min(int a, int b);    //取较小值函数源文件dllDemo.cpp
  

     2、dlldemo.cpp

          #include "dllDemo.h"
          extern "C" _declspec(dllexport)int Sum(int a, int b)
          {return a+b;}
          extern "C" _declspec(dllexport)int Max(int a, int b)
          {
              if(a>=b)
                    return a;
              else
                    return b;
          }
          extern "C" _declspec(dllexport)int Min(int a, int b)
          {
                if(a>=b)
                   return b;
               else
                   return a;
           }

二、测试用例部分

     

#include <iostream>
#include<windows.h>
using namespace std;

void main(void)
{
     typedef int(*pMax)(int a,int b);
     typedef int(*pMin)(int a,int b);
     pMax Max=NULL;
     pMin Min=NULL;
     HINSTANCE hDLL;
     hDLL=LoadLibrary("dllDemo.dll");//加载动态链接库MyDll.dll文件;
     Max=(pMax)GetProcAddress(hDLL,"Max");
     Min=(pMin)GetProcAddress(hDLL,"Min");
     if (Max)//如果取出函数成功,则执行下面的语句
    {
         int A=Max(5,8);
         cout<<"比较的结果为"<<A;
    }
    if (Min)
   {
         int B=Min(5,8);
         cout<<"比较的结果为"<<B;
   }
    FreeLibrary(hDLL);//卸载MyDll.dll文件;}
}

 

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
下面是一个简单示例,演示如何在 Python 中使用 `ctypes` 调用 C++ 编写的 DLL 文件: 1. 创建 C++ DLL 文件 首先,您需要创建一个 C++ 动态链接库(DLL)文件,其中包含您想要在 Python 中使用的 C++ 函数。下面是一个简单的示例,演示如何在 Visual Studio 中创建一个简单的 DLL 文件: ```cpp // SampleDLL.cpp #include "pch.h" #include "SampleDLL.h" extern "C" { int add(int x, int y) { return x + y; } } ``` 请注意,我们使用 `extern "C"` 来告诉编译器使用 C 语言的函数命名规则,以便在 Python 中调用。 2. 编译 DLL 文件 使用 Visual Studio,您可以将上述代码编译为 DLL 文件。在生成 DLL 文件之前,您需要将项目属性中的运行库设置为“多线程 DLL (/MD)”。 3. 在 Python 中使用 ctypes 调用 DLL 在 Python 中,您可以使用 `ctypes` 模块来调用 DLL 中的函数。下面是一个简单的示例: ```python import ctypes # 加载 DLL 文件 sample_dll = ctypes.CDLL('SampleDLL.dll') # 调用 DLL 中的函数 result = sample_dll.add(1, 2) # 输出结果 print(result) ``` 在上面的示例中,我们首先使用 `ctypes.CDLL()` 函数加载 DLL 文件。然后,我们可以使用 `sample_dll.add()` 来调用 DLL 文件中的 `add()` 函数。最后,我们输出了结果。 请确保在加载 DLL 文件时使用正确的文件名和路径。如果 DLL 文件不在当前工作目录中,则需要指定完整路径。 希望这个示例能够帮助您了解如何在 Python 中使用 `ctypes` 调用 C++ 编写的 DLL 文件。

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值