天天看点

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

一切以官网为准:https://docs.python.org/3.6/library/ctypes.html

以下为参考:

1、

在python中调用C语言生成的动态库,

返回结构体指针

,并进行输出!

mylib.c

(动态库源代码)

// 编译生成动态库: gcc -g -fPIC -shared -o libtest.so test.c  

#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;   

}  

编译:gcc -g -fPIC -shared -o libmylib.so test.c

call.py(python调用C语言生成的动态库):

[python] view plain copy

#!/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.name, p.contents.age)  

最后运行结果:

[plain]  ​

view plain  ​

copy

[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]$  

2、结构体嵌套

 Python Code 

<col>

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):

        ( "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)