用python调用C的动态链接库

本文介绍如何通过Python调用C语言编写的动态链接库(DLL),包括创建DLL工程、编写C代码、编译生成DLL文件及Python调用的具体步骤。

  暂时Python写得不好,有些东西还是用C写起来顺手,遇到这种情况怎么办呢…于是学习了一下python调用C动态链接库的方法。这样就可以将用C写好的函数提供给python使用了。

  首先要将先新建个DLL工程。例如我新建了dlllearning工程,内包含example.h和example.cpp两个文件。

  代码如下:

 1 //example.h
 2 #ifndef EXPORT_EXAMPLE_DLL
 3 #define EXAMPLE_API __declspec(dllimport)
 4 #else
 5 #define EXAMPLE_API __declspec(dllexport)
 6 #endif
 7 
 8 
 9 extern "C" {
10     EXAMPLE_API int max(int, int);
11     EXAMPLE_API int min(int, int);
12 }
 1 //example.cpp
 2 #define EXPORT_EXAMPLE_DLL
 3 #include "example.h"
 4 
 5 EXAMPLE_API int max(int a, int b) {
 6     return a > b ? a : b;
 7 }
 8 
 9 EXAMPLE_API int min(int a, int b) {
10     return a < b ? a : b;
11 }

关于__declspec(dllimport)的作用可以参考这篇博文:http://blog.youkuaiyun.com/mniwc/article/details/7993361

注意extern "c"是必须的,如果按照C++编译的话会有意想不到的问题发生,提示如下:

Traceback (most recent call last):
    mx = dlllearning.max(a, b)
  File "E:\Python34\lib\ctypes\__init__.py", line 364, in __getattr__
    func = self.__getitem__(name)
  File "E:\Python34\lib\ctypes\__init__.py", line 369, in __getitem__
    func = self._FuncPtr((name_or_ordinal, self))
AttributeError: function 'max' not found
[Finished in 0.2s]

 

编译生成dll文件,我们用python调用一下看看。

 

1 from ctypes import *
2 dlllearning = cdll.LoadLibrary('dlllearning.dll')
3 a = 413
4 b = 52
5 mx = dlllearning.max(a, b)
6 mn = dlllearning.min(a, b)
7 print(mx, mn)

 

输出结果:

413 52
[Finished in 0.2s]

 

顿时感觉打开了新世界的大门

转载于:https://www.cnblogs.com/kirai/p/4798830.html

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值