2016-09-14 1 views
1

다음 예와 NumPy와의 C-API (http://docs.scipy.org/doc/numpy/reference/c-api.html) (NumPy와 1.7+ 용),이 같은 cpp에있는 NumPy와 배열 데이터에 액세스하기 위해 노력하고있어 :

#include <Python.h> 
#include <frameobject.h> 
#define NPY_NO_DEPRECATED_API NPY_1_7_API_VERSION // TOGGLE OR NOT 
#include "numpy/ndarraytypes.h" 
#include "numpy/arrayobject.h" 
... 
// here I have passed "some_python_object" to the C code 
// .. and "some_python_object" has member "infobuf" that is a numpy array 
// 
unsigned long* fInfoBuffer; 
PyObject* infobuffer = PyObject_GetAttrString(some_python_object, "infobuf"); 
PyObject* x_array = PyArray_FROM_OT(infobuffer, NPY_UINT32); 
fInfoBuffer   = (unsigned long*)PyArray_DATA(x_array); // DOES NOT WORK WHEN API DEPRECATION IS TOGGLED 

error: cannot convert ‘PyObject* {aka _object*}’ to ‘PyArrayObject* {aka tagPyArrayObject*}’ for argument ‘1’ to ‘void* PyArray_DATA(PyArrayObject*)’ 

은 무엇 NumPy와 1.7+에서이 일을 합법적 인 방법이 될 것입니다 : 컴파일 할 때 API의 중단은, 내가 얻을 토글?

답변

1

적절한 컨테이너 의미론을 사용하여 C++ 컨테이너의 numpy 배열을 래핑하는 상위 수준 라이브러리를 사용해 볼 수 있습니다.

xtensorxtensor-python 바인딩을 사용해보세요.

테스트, HTML 문서에 대한 모든 상용구에 최소한의 C++ 확장 프로젝트를 생성하는 cookiecutter도 있습니다 및 setup.p ...

예 : C++ 코드

#include <numeric>      // Standard library import for std::accumulate 
#include "pybind11/pybind11.h"   // Pybind11 import to define Python bindings 
#include "xtensor/xmath.hpp"    // xtensor import for the C++ universal functions 
#define FORCE_IMPORT_ARRAY    // numpy C api loading 
#include "xtensor-python/pyarray.hpp"  // Numpy bindings 

double sum_of_sines(xt::pyarray<double> &m) 
{ 
    auto sines = xt::sin(m); 
    // sines does not actually hold any value, which are only computed upon access 
    return std::accumulate(sines.begin(), sines.end(), 0.0); 
} 

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

    m.def("sum_of_sines", sum_of_sines, 
     "Computes the sum of the sines of the values of the input array"); 

    return m.ptr(); 
} 

파이썬 코드 : C-API에 대해 참조

import numpy as np 
import xtensor_python_test as xt 

a = np.arange(15).reshape(3, 5) 
s = xt.sum_of_sines(v) 
s 
+0

질문, C++ 코드에 관련된 대답. C-API를 사용하면 어떻게 될까요? – rhody

+2

해당 C++ 코드는 C API를 사용하여 상위 수준 구조로 래핑합니다. 또한 원래 질문은 "나는 cpp에서 numpy 배열 데이터에 접근하려하고있다"고 말한다. – Quant