- // 编译生成动态库: gcc -g -fPIC -shared -o libtest.so test.c
- #include
- #include
- #include
- typedef struct StructPointerTest
- {
- char name[20];
- int age;
- }StructPointerTest, *StructPointer;
- StructPointer testfunction() // 返回结构体指针
- {
- StructPointer p = (StructPointer)malloc(sizeof(StructPointerTest));
- strcpy(p->name, "Joe");
- p->age = 20;
- return p;
- }
- #!/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("./libmylib.so")
- lib.testfunction.restype = POINTER(StructPointer) #指定函数返回值的数据结构
- p = lib.testfunction()
- print "%s: %d" %(, p.contents.age)
- [zcm@c_py #112]$make clean
- rm -f *.o libmylib.so
- [zcm@c_py #113]$make
- gcc -g -fPIC -shared -o libmylib.so test.c
- [zcm@c_py #114]$./call.py
- Joe: 20
- [zcm@c_py #115]$
1
2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 |
|
##python 文件
##文件名 pytest.py import ctypes mylib = ctypes.cdll.LoadLibrary( "cpptest.so") class sub_struct(ctypes.Structure): #子结构体 _fields_ = [ ( "test_char_p",ctypes.c_char_p), ( "test_int",ctypes.c_int) ] class struct_def(ctypes.Structure): _fields_ = [ ( "stru_string",ctypes.c_char_p), ( "stru_int", ctypes.c_int), ( "stru_arr_num", ctypes.c_char* 4), ("son_struct", sub_struct)#嵌套子结构体的名称( son_struct) 和结构( sub_struct) ] |