在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.so3 test.py
from ctypesimport
*
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.len4 测试结果
b'test 1'
b'test 2'
4
b'test 2'
4

本文展示了如何使用Python的ctypes模块调用C语言实现高效的数据交互,包括定义结构体、分配内存、传递数据及获取C函数返回值。
3018

被折叠的 条评论
为什么被折叠?



