我有一些用Python编写的代码,其输出是numpy数组,现在我想将该输出发送到C++
代码,在那里将执行大部分计算。
我试过使用cython的public cdef
,但我正在处理一些问题。谢谢你的帮助!下面是我的代码:
pymodule.pyx
:
from pythonmodule import result # result is my numpy array
import numpy as np
cimport numpy as np
cimport cython
@cython.boundscheck(False)
@cython.wraparound(False)
cdef public void cfunc():
print 'I am in here!!!'
cdef np.ndarray[np.float64_t, ndim=2, mode='c'] res = result
print res
一旦这是cythonized,我打电话给:
pymain.c
:
#include <Python.h>
#include <numpy/arrayobject.h>
#include "pymodule.h"
int main() {
Py_Initialize();
initpymodule();
test(2);
Py_Finalize();
}
int test(int a)
{
Py_Initialize();
initpymodule();
cfunc();
return 0;
}
我得到了NameError
的result
变量的C++
。我尝试用指针定义它,并从其他函数间接调用它,但是数组仍然不可见。我很确定答案很简单,但我就是不明白。谢谢你的帮助!
简短回答
NameError的原因是Python找不到模块,工作目录不会自动添加到您的^{} 。在} 和
C/C++
代码中使用^{setenv("PYTHONPATH", ".", 1);
可以解决这个问题。更长的答案
显然,有一个简单的方法可以做到这一点。使用包含已创建数组的python模块
pythonmodule.py
:您可以使用^{} 关键字构造
pymodule.pyx
来导出该数组。通过添加一些辅助函数,您通常不需要触碰Python或NumpyC-API
:函数}只是为了提取^{} 并复制它,这样您就可以完成Python并在不初始化解释器的情况下工作。
getNPArray
和getShape
分别返回数组及其形状。^添加{示例程序(在
C
,C++
中应该看起来相同)如下所示:始终记住设置:
在调用
Py_Initialize
之前,Python可以在工作目录中找到模块。其余的都是直截了当的。它可能需要一些额外的错误检查,肯定需要一个函数来释放分配的内存。
不含Cython的备用方式:
以您正在尝试的方式来做这件事是非常麻烦的,您最好使用^{} 将数组保存在
npy
二进制文件中,然后使用一些C++ library that reads that file for you。相关问题 更多 >
编程相关推荐