天天看點

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