ctypes:提取C库返回的结构的成员

ctypes:提取C库返回的结构的成员,第1张

ctypes:提取C库返回的结构的成员

主要是您需要

c_void_p
void *,并且必须使用取消引用返回值
.contents

这是一个工作示例(Windows)…

编辑 :我添加了一个铸造空指针成员的示例。

测试

#ifdef EXPORT#define API __declspec(dllexport)#else#define API __declspec(dllimport)#endiftypedef struct{        int a;        void* b;} mytype;API mytype* createMyType();API void destroyMyType(mytype* p);

测试

#define EXPORT#include <stdlib.h>#include <stdio.h>#include "test.h"API mytype* createMyType(){    int* tmp;    mytype* p = malloc(sizeof(mytype));    p->a = 5;    tmp = malloc(sizeof(int));    *tmp = 123;    p->b = tmp;    printf("%d %pn",p->a,p->b);    return p;}API void destroyMyType(mytype* p){    free(p->b);    free(p);}

test.py

from ctypes import *class mytype(Structure):    _fields_ = [('a',c_int),     ('b',c_void_p)]test = CDLL('test')createMyType = test.createMyTypecreateMyType.argtypes = NonecreateMyType.restype = POINTER(mytype)destroyMyType = test.destroyMyTypedestroyMyType.argtypes = POINTER(mytype),destroyMyType.restype = Nonet = createMyType()print('t is',t)print('t.a is',t.contents.a)print('t.b is',hex(t.contents.b))b = cast(t.contents.b,POINTER(c_int))print('*b is',b.contents)destroyMyType(t)

输出 :请注意,C代码中输出的void *b地址与所返回的整数匹配

t.contents.b
。将该
cast
整数转换为
POINTER(c_int)
可以提取内容的位置。

5 00000216C0E2A5D0t is <__main__.LP_mytype object at 0x00000216C30C4A48>t.a is 5t.b is 0x216c0e2a5d0*b is c_long(123)


欢迎分享,转载请注明来源:内存溢出

原文地址: https://outofmemory.cn/zaji/5661804.html

(0)
打赏 微信扫一扫 微信扫一扫 支付宝扫一扫 支付宝扫一扫
上一篇 2022-12-16
下一篇 2022-12-16

发表评论

登录后才能评论

评论列表(0条)

保存