从ctypes访问大内存缓冲区时出错

2024-09-26 22:51:38 发布

您现在位置:Python中文网/ 问答频道 /正文

在访问Python中的内存时出现“Segmentation fault(core dumped)”错误,该内存最初是在共享库中分配的

返回内存的函数声明为:

    extern "C" double *get_sound_data(int desc);
    extern "C" long long get_sound_data_size(int desc);

Python代码是:

from ctypes import *
cdll.LoadLibrary("libsomelib.so")
_lib = CDLL("libsomelib.so")

size = _lib.get_sound_data_size(desc)
data = _lib.get_sound_data(desc)
data = cast(data, POINTER(c_double))
arr = []
for i in range(size):
    arr.append(data[i])

对于小的缓冲区,比如10k项,它可以工作,但是当库返回几兆字节时,第一次尝试访问,即Python中的数据[0]

我看过这个页面,看起来很像https://bugs.python.org/issue13096

我在python2.7.12和3.5.2中遇到了同样的错误,操作系统是Linux


Tags: 内存datasizegetsolib错误extern
1条回答
网友
1楼 · 发布于 2024-09-26 22:51:38

你不能假装默认的返回类型是好的,并试图把你得到的无意义的结果转换成它应该是的类型(实际上,Python不应该有这样的默认值,但是现在更改它已经太晚了。)默认值是假设C函数返回C int,并且不能保证C int与指针大小相同;现在,可能不是

您需要实际设置argtypesrestype,以便能够通过ctypes安全地使用您的函数

get_sound_data = _lib.get_sound_data
get_sound_data_size = _lib.get_sound_data_size

get_sound_data.argtypes = (ctypes.c_int,)
get_sound_data.restype = ctypes.POINTER(ctypes.c_double)

get_sound_data_size.argtypes = (ctypes.c_int,)
get_sound_data_size.restype = ctypes.c_longlong

# Now use the functions

相关问题 更多 >

    热门问题