c++ - 将数组指针返回给 Python 时出错
问题描述
我的功能目的是制作自定义大小的数组并将其传递给 python。问题是每次我尝试这样做时,我都会得到
`python3' 中的错误:双重释放或损坏(fasttop)
或类似的东西。
我制作了一个此类错误的最小示例(我构建了 tst.so 共享库):
对于 C++:
int * lala = new int[1];
void def()
{
delete[] lala;
int * lala = new int[100];
}
extern "C" int * abc()
{
def();
return lala;
}
对于蟒蛇:
import ctypes
import numpy as np
from numpy.ctypeslib import ndpointer
import inspect
from os.path import abspath, dirname, join
fname = abspath(inspect.getfile(inspect.currentframe()))
libIII = ctypes.cdll.LoadLibrary(join(dirname(fname), 'tst.so'))
abc = libIII.abc
abc.restype = ndpointer(dtype=ctypes.c_int, shape=(100,))
abc.argtypes= None
asd = np.reshape(np.frombuffer(abc(), dtype = np.uint16), (100))
asd = np.reshape(np.frombuffer(abc(), dtype = np.uint16), (100))
asd = np.reshape(np.frombuffer(abc(), dtype = np.uint16), (100))
如果我制作int * lala = new int[100];
(与应有的大小相同),一切正常。难道我做错了什么?我应该如何删除旧数组并制作其他大小不同的数组?
解决方案
您正在声明一个 local lala
inside def
。为此分配内存不会改变全局lala
. 相反,请执行以下操作:
void def()
{
delete[] lala;
lala = new int[100]; // use global lala
}
推荐阅读
- gitlab-omnibus - Gitlab OpenID Connect 集成失败,证书验证失败
- c# - 单击按钮时向 DataGrid 添加新行
- angular - 如何在单元测试 Angular 5 中使用和处理来自服务的订阅响应以实现代码覆盖率?
- javascript - 没有数据的 Twitter 事件
- c# - 是否可以从 .Any() 中获取找到的值?
- reactjs - 容器内部通信
- php - 如何使用 URL 在带有 BS4 下拉菜单的 WP 中设置“posts_per_page”?
- c# - 如何在 DataGridView 中隐藏特定单元格的数据
- apache-spark - Spark 正在对已排序的分区进行排序,从而导致性能损失
- python - 如何将不存在的类成员函数动态转换为现有的类成员函数