首页 > 解决方案 > 在 Python 中从 C 中更改数组的数据

问题描述

我的目标是在 C 中创建一个数组,将其提供给 Cython/Python 函数,该函数会更改数据并将其返回给 C 并从 C 中读取数据。如果我不对数组做任何事情,我的程序就可以正常工作在python中并返回它。但是,一旦我在该函数内执行任何操作,我的程序就会在“函数之后:”-print 之后中断。

我当前的代码如下所示:

测试.pyx

cimport cython
import numpy as np
cimport numpy as np

cdef public c_array_to_numpy(input):
    cdef int[:,::1] temp = input
    temp[2,0] = 13
    return input

主程序

#define PY_SSIZE_T_CLEAN
#include <Python.h>
#include <ndarrayobject.h>
#include <stdio.h>
#include <Windows.h>
#include "test.h"

int main()
{
    Py_Initialize();
    import_array();

    int array1[2][3] = {{3, 7, 4}, {8, 5, 9}};

    int nd = 2;

    npy_intp const dims[2] = {2, 3};

    PyObject* new_array3 = PyArray_SimpleNewFromData(nd, dims, NPY_INT32,(void*) array1);

    Py_INCREF(new_array3);
    Py_INCREF(new_array3);

    printf("Before the function:\n");
    for (int i = 0; i < 2; i++)
    {
        for (int j = 0; j < 3; j++)
        {
            printf("%i ", array1[i][j]);
        }
        printf("\n");
    }

    printf("After the function:\n");
    PyObject* changed = c_array_to_numpy(new_array3);
    int* data_changed = PyArray_DATA(changed);
    printf("%i", changed[2]);


    Sleep(3000);
    Py_Finalize();

    return 0;
}

标签: pythoncapinumpycython

解决方案


推荐阅读