Python与C参数交互(结构指针).
来源:互联网 发布:狗爹域名注册 编辑:程序博客网 时间:2024/05/20 13:39
在Python中某些时候需要C做效率上的补充. 在实际应用中,需要做部分数据的交互. Python 可以通用 ctypes 模块很好地调用C. 下面演示了 Python 中调用C一个标准函数. 传递一个结构指针入. 得到C中分配内存数据 传递出. 希望对你的Python 学习有所帮助.
1 test.c
#include <stdio.h>
#include <stdlib.h>
typedef struct ...{
unsigned char words[10];
} keywords;
typedef struct ...{
keywords *kws;
unsigned int len;
} outStruct;
int test(outStruct *o)...{
unsigned int i=4;
o->kws = (keywords *)malloc(sizeof(unsigned char)*10*i);
strcpy(o->kws[0].words,"test 1");
strcpy(o->kws[1].words,"test 2");
o->len = i;
return 1;
}
#include <stdlib.h>
typedef struct ...{
unsigned char words[10];
} keywords;
typedef struct ...{
keywords *kws;
unsigned int len;
} outStruct;
int test(outStruct *o)...{
unsigned int i=4;
o->kws = (keywords *)malloc(sizeof(unsigned char)*10*i);
strcpy(o->kws[0].words,"test 1");
strcpy(o->kws[1].words,"test 2");
o->len = i;
return 1;
}
2 编译
gcc -c -fPIC -o test.o test.c
gcc -shared test.o -o test.so
gcc -shared test.o -o test.so
3 test.py
from ctypes import *
class keywords(Structure):
_fields_ = [
('words', c_char *10),]
class outStruct(Structure):
_fields_ = [
('kws', POINTER(keywords)),
('len', c_int),]
libc=CDLL("./test.so")
libc.test.argtypes = [POINTER(outStruct)]
o = outStruct()
ret = libc.test(byref(o))
print o.kws[0].words;
print o.kws[1].words;
print o.len
class keywords(Structure):
_fields_ = [
('words', c_char *10),]
class outStruct(Structure):
_fields_ = [
('kws', POINTER(keywords)),
('len', c_int),]
libc=CDLL("./test.so")
libc.test.argtypes = [POINTER(outStruct)]
o = outStruct()
ret = libc.test(byref(o))
print o.kws[0].words;
print o.kws[1].words;
print o.len
4 测试结果
$ python test.py
test 1
test 2
4
test 1
test 2
4
- Python与C参数交互(结构指针).
- Python与C参数交互---结构体指针作为参数 实例
- 【C语言提高37】结构体元素做函数参数与结构指针做函数参数
- C语言指针-----指针与结构体
- C语言数组参数与指针参数
- C语言数组参数与指针参数
- C语言数组参数与指针参数
- C语言数组参数与指针参数
- C语言数组参数与指针参数
- Python 与 C/C++ 的交互编程
- python与c语言交互---学习012
- 结构体指针与结构体名做函数参数对比
- C语言 指针与数组,结构体
- c语言结构体与指针
- 如何正确使用指针(指针作为输出型参数)与结构体指针作为函数参数
- Python Ctypes结构体指针处理(函数参数,函数返回)
- c指针与函数参数传递方式
- iOS: 学习笔记, Swift与C指针交互(译)
- NFS+DHCP+TFTP+KICKSTART无人值守安装RHEL4及NIS+autofs身份统一验证
- 超COOL的LIST样式
- 图层动态伸缩效果
- 利用C++Builder实现Google的Web服务
- 仿GOOGLE个性首页可移动图层效果
- Python与C参数交互(结构指针).
- Asp.net(C#)常用函数表
- 神墓最新章节列表
- Windows XP不用输入密码自动登录- -
- 恋爱达人 - 罗志祥在线试听,恋爱达人 - 罗志祥歌词,下载
- www.slaper.net
- qq空间开场动画代码
- Asp数据库还原函数
- Asp一次性将多外文件中的相同内容替换