python 从 C API 获取内存和释放内存数据

创建日期: 2023-07-03 16:46 | 作者: 风波 | 浏览次数: 14 | 分类: Python

C API

char * get_something(unsigned long size) {
    char* p = (char*)malloc(size_of(cahr) * size);
    return p;
}

void free_memory(void *p) {
    free(p);
}

Python 释放 C API 返回的内存

import ctypes

lib = ctypes.CDLL("./libmodelpre.so")

lib.get_something.argtypes = [ctypes.c_ulong] # 传入的参数 unsigned long
lib.get_something.restype = ctypes.c_void_p # 返回的参数

lib.free_memory.argtypes = [ctypes.c_void_p] # 传入的参数 void *
lib.free_memory.restype = None # 没有返回参数

content_ptr = lib.get_something(1024) # 获取数据内存指针
content = ctypes.string_at(content_ptr, 1024)
lib.free_memory(content_ptr) # 释放内存

注意⚠️:lib.free_memory 函数的参数必须是 ctypes.c_void_p,不然会报错 invalid pointer error

参考:https://devpress.csdn.net/python/63045c69c67703293080bd32.html

As David Schwartz pointed out, if you set restype to c_char_p, ctypes returns a regular Python string object. A simple way to get around this is to use a void * and cast the result:

14 浏览
7 爬虫
0 评论