将数组的指针返回给Python时出错

问题描述 投票:0回答:1

我的功能目的是制作自定义大小的数组,并将其传递给python。问题是每次我尝试这样做时,我都会得到

“ python3”中的错误:双重释放或损坏(快捷方式)

或类似的东西。

我制作了此类错误的最小示例(我建立了tst.so共享库):

对于c ++:

int * lala = new int[1];
void def()
{
    delete[] lala;
    int * lala = new int[100];
}
extern "C" int * abc()
{
    def();
    return lala;
}

对于python:

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.x ctypes
1个回答
1
投票

您在lala中声明了本地def。为此分配内存不会更改全局lala。相反,请执行以下操作:

void def()
{
    delete[] lala;
    lala = new int[100];   // use global lala
}  
© www.soinside.com 2019 - 2024. All rights reserved.