将C++数组发送到Python并返回(使用Numpy扩展C++)

row*_*man 29 c++ python arrays numpy c-api

我将发送一个c++数组到python函数,numpy array然后再返回另一个numpy array.在查阅了numpy文档和其他一些线程并调整代码后,最后代码正在运行,但我想知道这段代码是否以最佳方式编写,考虑到:

  • c++和之间不必要地复制数组numpy (python).
  • 正确解除变量的引用.
  • 简单直接的方法.

C++代码:

// python_embed.cpp : Defines the entry point for the console application.
//

#include "stdafx.h"

#define NPY_NO_DEPRECATED_API NPY_1_7_API_VERSION
#include "Python.h"
#include "numpy/arrayobject.h"
#include<iostream>

using namespace std;

int _tmain(int argc, _TCHAR* argv[])
{
    Py_SetProgramName(argv[0]);
    Py_Initialize();
    import_array()

    // Build the 2D array
    PyObject *pArgs, *pReturn, *pModule, *pFunc;
    PyArrayObject *np_ret, *np_arg;
    const int SIZE{ 10 };
    npy_intp dims[2]{SIZE, SIZE};
    const int ND{ 2 };
    long double(*c_arr)[SIZE]{ new long double[SIZE][SIZE] };
    long double* c_out;
    for (int i{}; i < SIZE; i++)
        for (int j{}; j < SIZE; j++)
            c_arr[i][j] = i * SIZE + j;

    np_arg = reinterpret_cast<PyArrayObject*>(PyArray_SimpleNewFromData(ND, dims, NPY_LONGDOUBLE, 
        reinterpret_cast<void*>(c_arr)));

    // Calling array_tutorial from mymodule
    PyObject *pName = PyUnicode_FromString("mymodule");
    pModule = PyImport_Import(pName);
    Py_DECREF(pName);
    if (!pModule){
        cout << "mymodule can not be imported" << endl;
        Py_DECREF(np_arg);
        delete[] c_arr;
        return 1;
    }
    pFunc = PyObject_GetAttrString(pModule, "array_tutorial");
    if (!pFunc || !PyCallable_Check(pFunc)){
        Py_DECREF(pModule);
        Py_XDECREF(pFunc);
        Py_DECREF(np_arg);
        delete[] c_arr;
        cout << "array_tutorial is null or not callable" << endl;
        return 1;
    }
    pArgs = PyTuple_New(1);
    PyTuple_SetItem(pArgs, 0, reinterpret_cast<PyObject*>(np_arg));
    pReturn = PyObject_CallObject(pFunc, pArgs);
    np_ret = reinterpret_cast<PyArrayObject*>(pReturn);
    if (PyArray_NDIM(np_ret) != ND - 1){ // row[0] is returned
        cout << "Function returned with wrong dimension" << endl;
        Py_DECREF(pFunc);
        Py_DECREF(pModule);
        Py_DECREF(np_arg);
        Py_DECREF(np_ret);
        delete[] c_arr;
        return 1;
    }
    int len{ PyArray_SHAPE(np_ret)[0] };
    c_out = reinterpret_cast<long double*>(PyArray_DATA(np_ret));
    cout << "Printing output array" << endl;
    for (int i{}; i < len; i++)
        cout << c_out[i] << ' ';
    cout << endl;

    // Finalizing
    Py_DECREF(pFunc);
    Py_DECREF(pModule);
    Py_DECREF(np_arg);
    Py_DECREF(np_ret);
    delete[] c_arr;
    Py_Finalize();
    return 0;
}
Run Code Online (Sandbox Code Playgroud)

在CodeReview中,有一个很棒的答案:链接......

Qua*_*ant 6

试用xtensorxtensor-python python绑定。

xtensor是一个C ++库,用于使用多维数组表达式进行数值分析。

xtensor提供

  • 一个支持numpy样式广播的可扩展表达式系统(请参阅numpy至xtensor备忘单)。
  • 遵循C ++标准库惯用法的API。
  • 操纵数组表达式并在xtensor上构建的工具。
  • Python的绑定,还有R和Julia的绑定。

使用例

初始化一个2-D数组,并计算其行之一与一维数组的总和。

#include <iostream>
#include "xtensor/xarray.hpp"
#include "xtensor/xio.hpp"

xt::xarray<double> arr1
  {{1.0, 2.0, 3.0},
   {2.0, 5.0, 7.0},
   {2.0, 5.0, 7.0}};

xt::xarray<double> arr2
  {5.0, 6.0, 7.0};

xt::xarray<double> res = xt::view(arr1, 1) + arr2;

std::cout << res;
Run Code Online (Sandbox Code Playgroud)

产出

{7, 11, 14}
Run Code Online (Sandbox Code Playgroud)

在C ++中创建一个Numpy样式的通用函数。

#include "pybind11/pybind11.h"
#include "xtensor-python/pyvectorize.hpp"
#include <numeric>
#include <cmath>

namespace py = pybind11;

double scalar_func(double i, double j)
{
    return std::sin(i) - std::cos(j);
}

PYBIND11_PLUGIN(xtensor_python_test)
{
    py::module m("xtensor_python_test", "Test module for xtensor python bindings");

    m.def("vectorized_func", xt::pyvectorize(scalar_func), "");

    return m.ptr();
}
Run Code Online (Sandbox Code Playgroud)

Python代码:

import numpy as np
import xtensor_python_test as xt

x = np.arange(15).reshape(3, 5)
y = [1, 2, 3, 4, 5]
z = xt.vectorized_func(x, y)
z
Run Code Online (Sandbox Code Playgroud)

产出

[[-0.540302,  1.257618,  1.89929 ,  0.794764, -1.040465],
 [-1.499227,  0.136731,  1.646979,  1.643002,  0.128456],
 [-1.084323, -0.583843,  0.45342 ,  1.073811,  0.706945]]
Run Code Online (Sandbox Code Playgroud)

  • 看起来很有趣,但是您正在使用 C++ 扩展 python,我需要使用 python 扩展 C++。 (2认同)

Mil*_*ore 6

我们将把二维数组传递给写在文件中的 python 函数pyCode.py

def pyArray (a):
    print ("Contents of a :")
    print (a)
    c = 0
    return c
Run Code Online (Sandbox Code Playgroud)
  1. 对于 C++ 到 Python: 文件:c_code.cpp
#include <Python.h>
#include <stdio.h>
#define NPY_NO_DEPRECATED_API NPY_1_7_API_VERSION
#include <numpy/arrayobject.h>

float Array [] = {1.2, 3.4, 5.6, 7.8};

int main (int argc, char *argv[])
{
    float *ptr = Array;
    PyObject *pName, *pModule, *pDict, *pFunc, *pArgs;
    npy_intp dims[1] = { 4 };
    PyObject *py_array;

    setenv("PYTHONPATH",".",1);
    Py_Initialize ();
    pName = PyUnicode_FromString ("pyCode");

    pModule = PyImport_Import(pName);

    pDict = PyModule_GetDict(pModule);

    import_array ();                                   

    py_array = PyArray_SimpleNewFromData(1, dims, NPY_FLOAT, ptr);
    

    pArgs = PyTuple_New (1);
    PyTuple_SetItem (pArgs, 0, py_array);

    pFunc = PyDict_GetItemString (pDict, (char*)"pyArray"); 

    if (PyCallable_Check (pFunc))
    {
        PyObject_CallObject(pFunc, pArgs);
    } else
    {
        cout << "Function is not callable !" << endl;
    }

    Py_DECREF(pName);
    Py_DECREF (py_array);                             
    Py_DECREF (pModule);
    Py_DECREF (pDict);
    Py_DECREF (pFunc);

    Py_Finalize ();                                    

    return 0;
}
Run Code Online (Sandbox Code Playgroud)

编译代码: g++ -g -fPIC c_code.cpp -o runMe -lpython3.5m -I/usr/include/python3.5m/

  1. 从 OpenCV Mat 到 Python:

文件: cv_mat_code.cpp

#include <iostream>
#include <Python.h>
#define NPY_NO_DEPRECATED_API NPY_1_7_API_VERSION
#include <numpy/arrayobject.h>

#include <opencv2/opencv.hpp>

using namespace cv;
using namespace std;

int main (int argc, char *argv[])
{
    float data[10] = { 1, 2, 3, 4, 5, 6, 7, 8, 9, 10};

    Mat mat1 (cv::Size (5, 2), CV_32F, data, Mat::AUTO_STEP);
    int row = 0;
    float *p = mat1.ptr<float>(row);

    cout << "Mat" << mat1 <<endl;

    PyObject *pName, *pModule, *pDict, *pFunc, *pArgs;
    npy_intp dims[2] = { 2, 5 };
    PyObject *py_array;

    setenv("PYTHONPATH",".",1);
    Py_Initialize ();
    pName = PyUnicode_FromString ("pyCode");
    
    pModule = PyImport_Import(pName);

    pDict = PyModule_GetDict(pModule);

    // Required for the C-API : http://docs.scipy.org/doc/numpy/reference/c-api.array.html#importing-the-api
    import_array ();

    py_array = PyArray_SimpleNewFromData(2, dims, NPY_FLOAT, p);

    pArgs = PyTuple_New (1);
    PyTuple_SetItem (pArgs, 0, py_array);

    pFunc = PyDict_GetItemString (pDict, (char*)"pyArray"); 

    if (PyCallable_Check (pFunc))
    {
        PyObject_CallObject(pFunc, pArgs);
    } else
    {
        cout << "Function is not callable !" << endl;
    }

    Py_DECREF(pName);
    Py_DECREF (py_array);                             
    Py_DECREF (pModule);
    Py_DECREF (pDict);
    Py_DECREF (pFunc);

    Py_Finalize ();                                  

    return 0;
}
Run Code Online (Sandbox Code Playgroud)

编译代码: g++ -g -fPIC cv_mat_code.cpp -o runMe -lpython3.5m -I/usr/include/python3.5m/ -I/usr/include/ -lopencv_core -lopencv_imgproc -lopencv_highgui


Mal*_*ick 5

作为另一种方式,无需直接接触 Python C API,可以使用pybind11(仅标头库):

CPP :

#include <pybind11/embed.h> // everything needed for embedding
#include <iostream>
#include <Eigen/Dense>  
#include<pybind11/eigen.h>
using Eigen::MatrixXd;
namespace py = pybind11;

int main() 
{    
  try 
  {          
        Py_SetProgramName("PYTHON");
        py::scoped_interpreter guard{}; 

        py::module py_test = py::module::import("py_test");

        MatrixXd m(2,2);
        m(0,0) = 1;
        m(1,0) = 2;
        m(0,1) = 3;
        m(1,1) = 4;

        py::object result = py_test.attr("test_mat")(m);

        MatrixXd res = result.cast<MatrixXd>();
        std::cout << "In c++ \n" << res << std::endl;
  }
  catch (std::exception ex)
  {
      std::cout << "ERROR   : " << ex.what() << std::endl;
  }
  return 1;
}
Run Code Online (Sandbox Code Playgroud)

py_test.py

def test_mat(m):
    print ("Inside python m = \n ",m )
    m[0,0] = 10
    m[1,1] = 99 
    return m
Run Code Online (Sandbox Code Playgroud)

输出 :

Inside python m =
  [[ 1.  3.]
  [ 2.  4.]]
In c++
10  3
 2 99
Run Code Online (Sandbox Code Playgroud)

请参阅官方文档

ps:我将Eigen用于 C++ 矩阵。

  • 谢谢你的好例子;我刚刚复制了它。发现这一行需要是:`std::cout &lt;&lt; "In c++ \n" &lt;&lt; res &lt;&lt; std::endl;` (2认同)

Meg*_*Ray 4

根据我的经验,这似乎非常有效。为了获得更高的效率,请尝试以下操作: http://ubuntuforums.org/showthread.php ?t=1266059

使用 weave,您可以在 Python 中内联 C/C++ 代码,这会很有用。

http://docs.scipy.org/doc/scipy-0.15.1/reference/ generated/scipy.weave.inline.html

以下是有关如何使用 Python 在许多不同语言之间进行交互的链接以及示例。

http://docs.scipy.org/doc/numpy/user/c-info.python-as-glue.html

这是如何使用 Cython 将 numpy 数组传递到 C++ 的快速简单示例:

http://www.birving.com/blog/2014/05/13/passing-numpy-arrays- Between-python-and/