Python使用ctypes访问C代码
工具:CodeBlocks
新建一个分享库工程( Shared library ),随便编写一个C代码的函数
// test.c #include <stdio.h> int fib(int n)
{
if( n == || n == )
{
return ;
}
else
{
return fib(n-) + fib(n-);
}
}
编译,在bin/Debug/目录中生成libtest.dll动态链接库文件,该文件可以通过ctypes模块进行访问使用,在该文件目录下新建一个test.py文件
# test.py import ctypes
import os _file_path = os.path.join(os.path.dirname(__file__), 'libtest.dll')
_mod = ctypes.cdll.LoadLibrary(_file_path) #加载动态库文件,返回一个类对象 <class 'ctypes.CDLL'> # int fib(int n)
fib = _mod.fib #获取类方法
fib.argtypes = (ctype_int,) #配置参数类型(tuple)
fib.restype = ctypes_int #配置返回值类型 #现在可以直接使用fib函数了
for i in range(10):
print( fib(i), end=' ' )
C函数的指针作为参数情况
// 参数有指针的函数
int divide(int a, int b, int *remainder) {
int quot = a / b;
*remainder = a % b;
return quot;
}
# 相应的处理办法 # int divide(int, int, int *)
_divide = _mod.divide
_divide.argtypes = (ctypes.c_int, ctypes.c_int, ctypes.POINTER(ctypes.c_int))
_divide.restype = ctypes.c_int def divide(x, y):
rem = ctypes.c_int()
quot = _divide(x, y, rem)
return quot,rem.value
C函数的数组作参数的情况
double avg(double *a, int n) {
int i;
double total = 0.0;
for (i = ; i < n; i++) {
total += a[i];
}
return total / n;
# 对于C中的数组,Python中没有固定的对应类型,所以要分类处理:
# Define a special type for the 'double *' argument
class DoubleArrayType:
def from_param(self, param): #对传进来的参数进行分发
typename = type(param).__name__
if hasattr(self, 'from_' + typename):
return getattr(self, 'from_' + typename)(param)
elif isinstance(param, ctypes.Array):
return param
else:
raise TypeError("Can't convert %s" % typename) # Cast from array.array objects
def from_array(self, param):
if param.typecode != 'd':
raise TypeError('must be an array of doubles')
ptr, _ = param.buffer_info()
return ctypes.cast(ptr, ctypes.POINTER(ctypes.c_double)) # Cast from lists/tuples
def from_list(self, param):
val = ((ctypes.c_double)*len(param))(*param)
return val from_tuple = from_list # Cast from a numpy array
def from_ndarray(self, param):
return param.ctypes.data_as(ctypes.POINTER(ctypes.c_double)) DoubleArray = DoubleArrayType()
_avg = _mod.avg
_avg.argtypes = (DoubleArray, ctypes.c_int)
_avg.restype = ctypes.c_double def avg(values):
return _avg(values, len(values))
Python使用ctypes访问C代码的更多相关文章
- 『Python CoolBook』使用ctypes访问C代码_下_demo进阶
点击进入项目 这一次我们尝试一下略微复杂的c程序. 一.C程序 头文件: #ifndef __SAMPLE_H__ #define __SAMPLE_H__ #include <math.h&g ...
- 『Python CoolBook』使用ctypes访问C代码_上_用法讲解
一.动态库文件生成 源文件hello.c #include "hello.h" #include <stdio.h> void hello(const char *na ...
- 第7.23节 Python使用property函数定义属性简化属性访问的代码实现
第7.23节 Python使用property函数定义属性简化属性访问的代码实现 一. 背景 在本章前面章节中,我们介绍了类相关的知识,并举例进行了说明,在这些例子中会定义一些形如 ...
- 如何在python中调用C语言代码
1.使用C扩展CPython还为开发者实现了一个有趣的特性,使用Python可以轻松调用C代码 开发者有三种方法可以在自己的Python代码中来调用C编写的函数-ctypes,SWIG,Python/ ...
- python学习(22) 访问数据库
原文链接:http://www.limerence2017.com/2018/01/11/python22/ 本文介绍python如何使用数据库方面的知识. SQLite SQLite是一种嵌入式数据 ...
- python程序调用C/C++代码
这篇用来记录在些模拟Canoe生成CAN数据桢工具时遇到的问题, 生成CAN数据桢,主要分为两个关注点: 1.如何从can信号名获取到can信号的ID长度以及信号的起始位,并将信号值按照一定的规则填写 ...
- 第14.7节 Python模拟浏览器访问实现http报文体压缩传输
一. 引言 在<第14.6节 Python模拟浏览器访问网页的实现代码>介绍了使用urllib包的request模块访问网页的方法.但上节特别说明http报文头Accept-Encodin ...
- python解析xml模块封装代码
在python中解析xml文件的模块用法,以及对模块封装的方法.原文转自:http://www.jbxue.com/article/16586.html 有如下的xml文件:<?xml vers ...
- 使用Python编程语言连接MySQL数据库代码
使用Python编程语言连接MySQL数据库代码,跟大家分享一下: 前几天我用python操作了mysql的数据库,发现非常的有趣,而且python操作mysql的方法非常的简单和快速,所以我把代码分 ...
随机推荐
- nsstring遍历汉子
NSString *mytimestr=@"好人一生平安"; size_t length = [mytimestr length]; ; i < length; i++) { ...
- inception cenOS 安装
inception手册http://mysql-inception.github.io/inception-document/install/ 执行命令sh inception_build.sh,ce ...
- MYSQL 命令行导入导出数据库文件
MYSQL命令行导入数据库 1.首先通过命令行进入到mysql安装目录的bin目录下,比如我输入的命令为: cd E:\MySQL\MySQL Server 5.5\bin,输入如下命令: mysql ...
- 关于Application的onCreate以及Activity生命周期在源码里都是什么时候调用的
在ActivityThread.handleLaunchActivity中 Activity a = performLaunchActivity(r, customIntent);这一方法最终回调目标 ...
- Linux修改SSH端口和禁止Root远程登陆
Linux修改ssh端口22 vi /etc/ssh/ssh_config vi /etc/ssh/sshd_config 然后修改为port 8888 以root身份service sshd res ...
- @PostConstruct 和 @PreDestory
关于在spring 容器初始化 bean 和销毁前所做的操作定义方式有三种: 第一种:通过@PostConstruct 和 @PreDestroy 方法 实现初始化和销毁bean之前进行的操作 第二 ...
- Winform制作圆弧panel
原理就是手动去画边框留出四个角 然后绘制四张圆弧的图片到panel上 public class ArcPanel : Panel { protected override void OnPaint(P ...
- hdu 1531 King
首先吐槽一下这个题目的题意描述,我看了半天才明白. 下标全部都是乱标的!!!!出题者能不能规范一点下标的写法!!!! 差分约束系统 #include<cstdio> #include< ...
- html5权威指南:html base标签
html base标签:http://www.cnblogs.com/yuepeng/archive/2010/08/30/1812498.html
- OpenCL( 一)
#include <CL/cl.h> #include <iostream> #include <string> #include <fstream> ...