将C++双数组传递给Python会导致崩溃

2024-10-02 22:26:40 发布

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

我试图从C++到Python传递一个双数组,遇到了一个问题。我运行一个脚本来创建一个包含数据的二进制文件,然后将数据读回数组,并尝试将数组传递给Python。我在这里遵循了建议:how to return array from c function to python using ctypes在我通过google找到的其他页面中。我可以编写一个运行良好的通用示例(类似于上面链接的数组),但是当我尝试传递从二进制文件(下面的代码)读取的数组时,程序会崩溃,并出现“地址处未处理的异常”(ucrtbase.dll)在python.exe:一个无效参数被传递给了一个认为无效参数是致命的函数如果有人有见识的话。你知道吗

方法论:

现在,我只是想学习—这就是为什么我要经历一个复杂的过程,即保存到磁盘、加载和传递到Python。最后,我将在科学模拟中使用它,从磁盘读取的数据需要由分布式计算/超级计算机生成。我想使用Python来简化绘图(MatPultLIB)和C++的速度(迭代计算等)。你知道吗

所以,继续我的代码。这将生成二进制文件:

for (int zzz = 0; zzz < arraysize; ++zzz)
{
    for (int yyy = 0; yyy < arraysize; ++yyy)
    {
        for (int xxx = 0; xxx < arraysize; ++xxx)
        {//totalBatP returns a 3 element std::vector<double> - dblArray3_t is basically that with a few overloaded operators (+,-,etc)
            dblArray3_t BatP = B.totalBatP({ -5 + xxx * stepsize, -5 + yyy * stepsize, -5 + zzz * stepsize }, 37);
            for (int bbb = 0; bbb < 3; ++bbb)
            {
                dataarray[loopind] = BatP[bbb];
                ++loopind;
                ...(end braces here)
FILE* binfile;
binfile = fopen("MBdata.bin", "wb");
fwrite(dataarray, 8, 3 * arraysize * arraysize * arraysize, binfile);

读取文件的代码:

DLLEXPORT double* readDblBin(const std::string filename, unsigned int numOfDblsToRead)
{
    char* buffer = new char[numOfDblsToRead];
    std::ifstream binFile;
    binFile.open(filename, std::ios::in | std::ios::binary);
    binFile.read(buffer, numOfDblsToRead);
    double* dataArray = (double*)buffer;
    binFile.close();

    return dataArray;
}

以及接收数组的Python代码:

def readBDataWrapper(filename, numDblsToRead):
    fileIO = ctypes.CDLL('./fileIO.dll')
    fileIO.readDblBin.argtypes = (ctypes.c_char_p, ctypes.c_uint)
    fileIO.readDblBin.restype = ctypes.POINTER(ctypes.c_double)

    return fileIO.readDblBin(filename, numDblsToRead)

Tags: 文件代码for数组ctypesfileioxxxint
2条回答

我想出来了-至少它看起来起作用了。问题在于第一个代码块生成的二进制文件。我用ofstream替换了c字。我的假设是,也许我用代码写错了磁盘。不管怎样,它现在似乎起作用了。你知道吗

已替换:

FILE* binfile;
binfile = fopen("MBdata.bin", "wb");
fwrite(dataarray, 8, 3 * arraysize * arraysize * arraysize, binfile);

使用:

std::ofstream binfile;
binfile.open("MBdata.bin", std::ios::binary | std::ios::out);
binfile.write(reinterpret_cast<const char*>(dataarray), std::streamsize(totaliter * sizeof(double)));
binfile.close();

一个可能的问题是这里

char* buffer = new char[numOfDblsToRead];

在这里分配numOfDblsToRead字节。你可能想要numOfDblsToRead * sizeof(double)。你知道吗

与从文件读取相同,只读取numOfDblsToRead字节。你知道吗

相关问题 更多 >