用python调用C的动态链接库
2015-09-10 18:43
609 查看
暂时Python写得不好,有些东西还是用C写起来顺手,遇到这种情况怎么办呢…于是学习了一下python调用C动态链接库的方法。这样就可以将用C写好的函数提供给python使用了。
首先要将先新建个DLL工程。例如我新建了dlllearning工程,内包含example.h和example.cpp两个文件。
代码如下:
关于__declspec(dllimport)的作用可以参考这篇博文:http://blog.csdn.net/mniwc/article/details/7993361
注意extern "c"是必须的,如果按照C++编译的话会有意想不到的问题发生,提示如下:
编译生成dll文件,我们用python调用一下看看。
输出结果:
顿时感觉打开了新世界的大门
首先要将先新建个DLL工程。例如我新建了dlllearning工程,内包含example.h和example.cpp两个文件。
代码如下:
//example.h #ifndef EXPORT_EXAMPLE_DLL #define EXAMPLE_API __declspec(dllimport) #else #define EXAMPLE_API __declspec(dllexport) #endif extern "C" { EXAMPLE_API int max(int, int); EXAMPLE_API int min(int, int); }
//example.cpp #define EXPORT_EXAMPLE_DLL #include "example.h" EXAMPLE_API int max(int a, int b) { return a > b ? a : b; } EXAMPLE_API int min(int a, int b) { return a < b ? a : b; }
关于__declspec(dllimport)的作用可以参考这篇博文:http://blog.csdn.net/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调用一下看看。
from ctypes import * dlllearning = cdll.LoadLibrary('dlllearning.dll') a = 413 b = 52 mx = dlllearning.max(a, b) mn = dlllearning.min(a, b) print(mx, mn)
输出结果:
413 52 [Finished in 0.2s]
顿时感觉打开了新世界的大门
相关文章推荐
- [LeetCode]题解(python):007-Reverse Integer
- python随机数函数
- 初学Python
- python写入文件乱码处理
- python调用C函数
- [LeetCode]题解(python):006-ZigZag Conversion
- Python+OpenCV学习(6)---傅里叶变换
- 使用python实现自动“扫描检测硬件改动”功能
- crontab 定时运行python程序遇到的一个错误
- python twisted 框架 client 和server 模型
- Python 支付宝支付代码
- 用Python写了个websocket即时聊天网页(含客户端、服务端代码)
- Python自动化运维之简易ssh自动登录
- Python的二进制位运算
- python国内镜像站
- Python脚本开头两行-源代码编码
- Python 基础语法(四)
- Python 基础语法(三)
- Python 基础语法(二)
- Python 基础语法(一)