【python C结构体】Python Ctypes结构体指针处理(函数参数,函数返回)

一切以官网为准:https://docs.python.org/3.6/library/ctypes.html
以下为参考:
1、 在python中调用C语言生成的动态库, 返回结构体指针 ,并进行输出!
mylib.c (动态库源代码)
  1. // 编译生成动态库: gcc -g -fPIC -shared -o libtest.so test.c  
  2.   
  3. #include   
  4. #include   
  5. #include   
  6.   
  7. typedef struct StructPointerTest  
  8. {  
  9.     char name[20];  
  10.     int age;  
  11. }StructPointerTest, *StructPointer;  
  12.   
  13. StructPointer testfunction()    // 返回结构体指针  
  14. {   
  15.     StructPointer p = (StructPointer)malloc(sizeof(StructPointerTest));   
  16.     strcpy(p->name, "Joe");  
  17.     p->age = 20;  
  18.       
  19.     return p;   
  20. }  
编译:gcc -g -fPIC -shared -o libmylib.so test.c
call.py(python调用C语言生成的动态库):
[python] view plain copy
  1. #!/bin/env python  
  2. # coding=UTF-8  
  3.   
  4. from ctypes import *  
  5.   
  6. #python中结构体定义  
  7. class StructPointer(Structure):  
  8.     _fields_ = [("name", c_char * 20), ("age", c_int)]  
  9.   
  10. if __name__ == "__main__":  
  11.     lib = cdll.LoadLibrary("./libmylib.so")  
  12.     lib.testfunction.restype = POINTER(StructPointer)  #指定函数返回值的数据结构
  13.     p = lib.testfunction()  
  14.   
  15.     print "%s: %d" %(p.contents.name, p.contents.age)  
最后运行结果:
[plain]  view plain  copy
  1. [zcm@c_py #112]$make clean  
  2. rm -f *.o libmylib.so 
  3. [zcm@c_py #113]$make  
  4. gcc -g -fPIC -shared -o libmylib.so test.c  
  5. [zcm@c_py #114]$./call.py   
  6. Joe: 20  
  7. [zcm@c_py #115]$  
转自:https://blog.csdn.net/joeblackzqq/article/details/10441017
2、结构体嵌套
 Python Code 
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)

    ]
摘自: https://blog.csdn.net/caobin0825/article/details/79642679
  • 0
    点赞
  • 4
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值