Python调用C,主要是依靠Python的ctypes调用动态链接库
返回“简单类型”
C代码:
int multiply(int num1, int num2) { return num1 * num2; }
gcc命令:
gcc -c -fPIC libtest.c
gcc -shared libtest.o -o libtest.so
Python调用:
>>> from ctypes import * >>> import os >>> libtest = cdll.LoadLibrary(os.getcwd() + ‘/libtest.so‘) >>> print libtest.multiply(2, 2) 4
返回“结构体类型”
C代码:
typedef struct pointer_test_s { char name[20]; int age; }pointer_test_t, *struct_pointer; struct_pointer test() // 返回结构体指针 { struct_pointer p = (struct_pointer)malloc(sizeof(pointer_test_t)); strcpy(p->name, "Joe"); p->age = 20; return p; }
Python代码:
#!/bin/env python # coding=UTF-8 from ctypes import * #python中结构体定义 class StructPointer(Structure): _fields_ = [("name", c_char * 20), ("age", c_int)] if __name__ == "__main__": lib = cdll.LoadLibrary("./libtest.so") lib.test.restype = POINTER(StructPointer) p = lib.test() print "%s: %d" %(p.contents.name, p.contents.age)
附类型对照: