将一个NUMPY数组传递给C++

2024-09-27 20:15:20 发布

您现在位置:Python中文网/ 问答频道 /正文

我有一些用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;
}

我得到了NameErrorresult变量的C++。我尝试用指针定义它,并从其他函数间接调用它,但是数组仍然不可见。我很确定答案很简单,但我就是不明白。谢谢你的帮助!


Tags: 代码pyimportnumpyincludeasnp数组
1条回答
网友
1楼 · 发布于 2024-09-27 20:15:20

简短回答

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 <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

函数getNPArraygetShape分别返回数组及其形状。^添加{}只是为了提取^{}并复制它,这样您就可以完成Python并在不初始化解释器的情况下工作。

示例程序(在CC++中应该看起来相同)如下所示:

#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的备用方式:

以您正在尝试的方式来做这件事是非常麻烦的,您最好使用^{}将数组保存在npy二进制文件中,然后使用一些C++ library that reads that file for you

相关问题 更多 >

    热门问题