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

Python CTYPE:如何释放内存?获取无效的指针错误

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

Python CTYPE:如何释放内存?获取无效的指针错误

正如David Schwartz指出的那样,如果将restype设置为

c_char_p
,则ctypes将返回常规的Python字符串对象。解决此问题的一种简单方法是使用a
void*
并强制转换结果:

string.c:

#include <stdlib.h>#include <string.h>#include <stdio.h>char *get(void){    char *buf = "Hello World";    char *new_buf = strdup(buf);    printf("allocated address: %pn", new_buf);    return new_buf;}void freeme(char *ptr){    printf("freeing address: %pn", ptr);    free(ptr);}

Python用法:

from ctypes import *lib = cdll.LoadLibrary('./string.so')lib.freeme.argtypes = c_void_p,lib.freeme.restype = Nonelib.get.argtypes = []lib.get.restype = c_void_p>>> ptr = lib.get()allocated address: 0x9facad8>>> hex(ptr)'0x9facad8'>>> cast(ptr, c_char_p).value'Hello World'>>> lib.freeme(ptr)freeing address: 0x9facad8

您还可以使用的子类

c_char_p
。事实证明,ctypes不会
getfunc
为简单类型的子类调用。

class c_char_p_sub(c_char_p):    passlib.get.restype = c_char_p_sub

value
属性返回字符串。您可以将参数保留
freeme
为更通用
c_void_p
。那可以接受任何指针类型或整数地址。



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

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

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