简短回答
NameError的原因是Python找不到模块,工作目录不会自动添加到您的^{}。在C/C++代码中使用^{}和setenv("PYTHONPATH", ".", 1);可以解决这个问题。
更长的答案
显然,有一个简单的方法可以做到这一点。使用包含已创建数组的python模块pythonmodule.py:import numpy as np
result = np.arange(20, dtype=np.float).reshape((2, 10))
您可以使用pymodule.pyx来导出该数组。通过添加一些辅助函数,您通常不需要触碰Python或NumpyC-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 result
cdef public int getShape(np.ndarray arr, int shape):
""" Return Shape of the Array based on shape par value. """
return arr.shape[1] if shape else 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 = malloc(m * sizeof(float *))
if not tmp:
raise MemoryError()
# Allocate rows
for j in range(m):
tmp[j] = 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分别返回数组及其形状。^添加{}只是为了提取^{}并复制它,这样您就可以完成Python并在不初始化解释器的情况下工作。
示例程序(在C,C++中应该看起来相同)如下所示:#include
#include "numpy/arrayobject.h"
#include "pyxmod.h"
#include
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的备用方式:
以您正在尝试的方式来做这件事是非常麻烦的,您最好使用^{}将数组保存在npy二进制文件中,然后使用一些C++ library that reads that file for you。