python - 在 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;
}
解决方案
推荐阅读
- reactjs - React-router 更改位置但不渲染组件
- mysql - 基于逗号分隔的字符串在 MySQL 表中选择多行
- windows - 将 laravel 项目移动到另一个目录
- r - 如何为 facet_wrap 自动调整每个 facet 的宽度?
- python - 从另一个参数获取参数
- c++ - 无缘无故地抛出一个实例
- r - 如何在 r 中调用后将 xlabel 和 ylabel 添加到基本图?
- react-native - 如何运行特定的 fastlane 任务,例如“pilot”
- amazon-s3 - 通过 Lambda 和 API Gateway 从 AWS S3 下载图像——使用 fetch 类
- javascript - Storybook React 及其示例组件不起作用