【python调用C结构体】Python Ctypes结构体指针处理

mylib.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 = 30;

    return p;
}

// gcc -g -fPIC -shared -o libmylib.so mylib.c

编译产生 libmylib.so 文件

demo.py 文件

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))  # b'Joe': 30

***结构体嵌套***

import ctypes

mylib = ctypes.cdll.LoadLibrary("cpptest.so")

class 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)
    ]

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

你可能感兴趣的:(c语言,c++,开发语言)