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 avoid *
and cast the result: