简答
NameError 的原因是 Python 找不到模块,工作目录没有自动添加到您的 PYTHONPATH。在 C/C++ 代码中使用 setenv 和 setenv("PYTHONPATH", ".", 1); 可以解决此问题。
更长的答案
显然,有一种简单的方法可以做到这一点。使用包含已创建数组的 python 模块pythonmodule.py:
import numpy as np
result = np.arange(20, dtype=np.float).reshape((2, 10))
您可以使用 public 关键字构建 pymodule.pyx 以导出该数组。通过添加一些辅助功能,您通常不需要接触 Python 和 Numpy C-API:
from pythonmodule import result
from libc.stdlib cimport malloc
import numpy as np
cimport numpy as np
cdef public np.ndarray getNPArray():
""" Return array from pythonmodule. """
return <np.ndarray>result
cdef public int getShape(np.ndarray arr, int shape):
""" Return Shape of the Array based on shape par value. """
return <int>arr.shape[1] if shape else <int>arr.shape[0]
cdef public void copyData(float *** dst, np.ndarray src):
""" Copy data from src numpy array to dst. """
cdef float **tmp
cdef int i, j, m = src.shape[0], n=src.shape[1];
# Allocate initial pointer
tmp = <float **>malloc(m * sizeof(float *))
if not tmp:
raise MemoryError()
# Allocate rows
for j in range(m):
tmp[j] = <float *>malloc(n * sizeof(float))
if not tmp[j]:
raise MemoryError()
# Copy numpy Array
for i in range(m):
for j in range(n):
tmp[i][j] = src[i, j]
# Assign pointer to dst
dst[0] = tmp
函数getNPArray 和getShape 分别返回数组及其形状。添加copyData 只是为了提取ndarray.data 并复制它,这样您就可以在不初始化解释器的情况下完成Python 并工作。
示例程序(C、C++ 应该看起来相同)如下所示:
#include <Python.h>
#include "numpy/arrayobject.h"
#include "pyxmod.h"
#include <stdio.h>
void printArray(float **arr, int m, int n);
void getArray(float ***arr, int * m, int * n);
int main(int argc, char **argv){
// Holds data and shapes.
float **data = NULL;
int m, n;
// Gets array and then prints it.
getArray(&data, &m, &n);
printArray(data, m, n);
return 0;
}
void getArray(float ***data, int * m, int * n){
// setenv is important, makes python find
// modules in working directory
setenv("PYTHONPATH", ".", 1);
// Initialize interpreter and module
Py_Initialize();
initpyxmod();
// Use Cython functions.
PyArrayObject *arr = getNPArray();
*m = getShape(arr, 0);
*n = getShape(arr, 1);
copyData(data, arr);
if (data == NULL){ //really redundant.
fprintf(stderr, "Data is NULL\n");
return ;
}
Py_DECREF(arr);
Py_Finalize();
}
void printArray(float **arr, int m, int n){
int i, j;
for(i=0; i < m; i++){
for(j=0; j < n; j++)
printf("%f ", arr[i][j]);
printf("\n");
}
}
永远记得设置:
setenv("PYTHONPATH", ".", 1);
在之前调用Py_Initialize,以便 Python 可以在工作目录中找到模块。
其余的都很简单。它可能需要一些额外的错误检查,并且肯定需要一个函数来释放分配的内存。
不带 Cython 的替代方式:
按照您尝试的方式进行操作比它的价值要麻烦得多,您最好使用numpy.save 将您的数组保存在npy 二进制文件中,然后使用一些C++ library that reads that file for you。