首页 > 解决方案 > 将数组指针返回给 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];(与应有的大小相同),一切正常。难道我做错了什么?我应该如何删除旧数组并制作其他大小不同的数组?

标签: c++python-3.xctypes

解决方案


您正在声明一个 local lalainside def。为此分配内存不会改变全局lala. 相反,请执行以下操作:

void def()
{
    delete[] lala;
    lala = new int[100];   // use global lala
}  

推荐阅读