栏目分类:
子分类:
返回
名师互学网用户登录
快速导航关闭
当前搜索
当前分类
子分类
实用工具
热门搜索
名师互学网 > IT > 面试经验 > 面试问答

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

面试问答 更新时间: 发布时间: IT归档 最新发布 模块sitemap 名妆网 法律咨询 聚返吧 英语巴士网 伯小乐 网商动力

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)


转载请注明:文章转载自 www.mshxw.com
本文地址:https://www.mshxw.com/it/659737.html
我们一直用心在做
关于我们 文章归档 网站地图 联系我们

版权所有 (c)2021-2022 MSHXW.COM

ICP备案号:晋ICP备2021003244-6号