【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

posted on 2022-10-04 01:29  bdy  阅读(493)  评论(0编辑  收藏  举报

导航