yue*_*uez 5 c++ python numpy cython
谢谢大家.
我想知道什么是#include所有numpy标头的正确方法,以及使用Cython和C++解析numpy数组的正确方法.以下是尝试:
// cpp_parser.h
#ifndef _FUNC_H_
#define _FUNC_H_
#include <Python.h>
#include <numpy/arrayobject.h>
void parse_ndarray(PyObject *);
#endif
Run Code Online (Sandbox Code Playgroud)
我知道这可能是错的,我也尝试了其他选择,但没有一个可行.
// cpp_parser.cpp
#include "cpp_parser.h"
#include <iostream>
using namespace std;
void parse_ndarray(PyObject *obj) {
if (PyArray_Check(obj)) { // this throws seg fault
cout << "PyArray_Check Passed" << endl;
} else {
cout << "PyArray_Check Failed" << endl;
}
}
Run Code Online (Sandbox Code Playgroud)
该PyArray_Check程序抛出段错误.PyArray_CheckExact不扔,但它不是我想要的.
# parser.pxd
cdef extern from "cpp_parser.h":
cdef void parse_ndarray(object)
Run Code Online (Sandbox Code Playgroud)
并且实现文件是:
# parser.pyx
import numpy as np
cimport numpy as np
def py_parse_array(object x):
assert isinstance(x, np.ndarray)
parse_ndarray(x)
Run Code Online (Sandbox Code Playgroud)
该setup.py脚本
# setup.py
from distutils.core import setup, Extension
from Cython.Build import cythonize
import numpy as np
ext = Extension(
name='parser',
sources=['parser.pyx', 'cpp_parser.cpp'],
language='c++',
include_dirs=[np.get_include()],
extra_compile_args=['-fPIC'],
)
setup(
name='parser',
ext_modules=cythonize([ext])
)
Run Code Online (Sandbox Code Playgroud)
最后是测试脚本:
# run_test.py
import numpy as np
from parser import py_parse_array
x = np.arange(10)
py_parse_array(x)
Run Code Online (Sandbox Code Playgroud)
我用上面的所有脚本创建了一个git repo.
https://github.com/giantwhale/study_cython_numpy/
已经挣扎了好几天.如果你能帮帮我,我真的很感激.
--------------------更新------------------谢谢@ oz1的回复.知道我实际上可以#include在Cython中做很有帮助.但是,我真的在寻找使用纯C++的方法,因为我有一些必须在C++中实现的关键部分.
例如,如果我想PyArray_Check在C++中使用以获取numpy数组中的元素总数,我将编写以下内容:
// cpp_parser.h
#ifndef _FUNC_H_
#define _FUNC_H_
#include <Python.h>
#include <numpy/arrayobject.h>
void parse_ndarray(PyObject *);
#endif
Run Code Online (Sandbox Code Playgroud)
但是,这会导致更多错误.它在编译时失败,并显示以下错误消息:
// cpp_parser.cpp
#include "cpp_parser.h"
#include <iostream>
using namespace std;
void parse_ndarray(PyObject *obj) {
if (PyArray_Check(obj)) { // this throws seg fault
cout << "PyArray_Check Passed" << endl;
} else {
cout << "PyArray_Check Failed" << endl;
}
}
Run Code Online (Sandbox Code Playgroud)
我用谷歌搜索了这个术语PyArray_CheckExact,似乎我也应该用C++调用这个函数.我真的不知道如何做到这一点.
另外,我在Apache Arrow项目中找到了一个代码示例,其中包含以下内容:(https://github.com/apache/arrow/blob/master/cpp/src/arrow/python/numpy_interop.h)
# parser.pxd
cdef extern from "cpp_parser.h":
cdef void parse_ndarray(object)
Run Code Online (Sandbox Code Playgroud)
我尝试使用/不使用-DNPY_1_7_API_VERSION,但我仍然无法使其工作.
有任何想法吗?
快速修复(请继续阅读以获取更多详细信息和更复杂的方法):
您需要PyArray_API通过调用import_array()以下方法在每个使用numpy-stuff的cpp文件中初始化变量:
//it is only a trick to ensure import_array() is called, when *.so is loaded
//just called only once
int init_numpy(){
import_array(); // PyError if not successful
return 0;
}
const static int numpy_initialized = init_numpy();
void parse_ndarraray(PyObject *obj) { // would be called every time
if (PyArray_Check(obj)) {
cout << "PyArray_Check Passed" << endl;
} else {
cout << "PyArray_Check Failed" << endl;
}
}
Run Code Online (Sandbox Code Playgroud)
也可以使用_import_array,如果不成功则返回负数,以使用自定义错误处理.请看这里的定义import_array.
先进的解决方案:
建议的解决方案很快,但如果使用numpy有多个cpp,则会有很多PyArray_API初始化的实例.
如果_import_array()/import_array()没有定义为静态,则可以避免这种情况Py_Initialize(),但除了一个翻译单元之外.对于那些转换单元,numpy_initialized必须在main包含之前定义宏.
然而,我们需要一个定义了这个符号的翻译单元.对于此转换单元,init_numpy()不得定义宏.
但是,如果不定义宏,Py_Initialize()我们将只获得一个静态符号,即其他转换单元不可见,因此链接器将失败.原因是:如果有两个库并且每个人都定义了一个,PyArray_API那么我们将有一个符号的多重定义,并且链接器将失败,即我们不能将这两个库一起使用.
因此,通过定义PyArray_API为extern前每包括NO_IMPORT_ARRAY我们有我们自己的numpy/arrayobject.h-name,这不会与其他库发生冲突.
把它们放在一起:
答: use_numpy.h - 包含numpy功能的标题即NO_IMPORT_ARRAY
//use_numpy.h
//your fancy name for the dedicated PyArray_API-symbol
#define PY_ARRAY_UNIQUE_SYMBOL MY_PyArray_API
//this macro must be defined for the translation unit
#ifndef INIT_NUMPY_ARRAY_CPP
#define NO_IMPORT_ARRAY //for usual translation units
#endif
//now, everything is setup, just include the numpy-arrays:
#include <numpy/arrayobject.h>
Run Code Online (Sandbox Code Playgroud)
B: PY_ARRAY_UNIQUE_SYMBOL - 用于初始化全局的翻译单元PyArray_API:
//init_numpy_api.cpp
//first make clear, here we initialize the MY_PyArray_API
#define INIT_NUMPY_ARRAY_CPP
//now include the arrayobject.h, which defines
//void **MyPyArray_API
#inlcude "use_numpy.h"
//now the old trick with initialization:
int init_numpy(){
import_array();// PyError if not successful
return 0;
}
const static int numpy_initialized = init_numpy();
Run Code Online (Sandbox Code Playgroud)
C:只包括PY_ARRAY_UNIQUE_SYMBOL只要你需要numpy的,它会定义MY_FANCY_LIB_PyArray_API:
//example
#include "use_numpy.h"
...
PyArray_Check(obj); // works, no segmentation error
Run Code Online (Sandbox Code Playgroud)
你为什么需要它:
当我使用调试符号构建扩展时:
extra_compile_args=['-fPIC', '-O0', '-g'],
extra_link_args=['-O0', '-g'],
Run Code Online (Sandbox Code Playgroud)
并使用gdb运行它:
gdb --args python run_test.py
(gdb) run
--- Segmentation fault
(gdb) disass
Run Code Online (Sandbox Code Playgroud)
我可以看到以下内容:
0x00007ffff1d2a6d9 <+20>: mov 0x203260(%rip),%rax
# 0x7ffff1f2d940 <_ZL11PyArray_API>
0x00007ffff1d2a6e0 <+27>: add $0x10,%rax
=> 0x00007ffff1d2a6e4 <+31>: mov (%rax),%rax
...
(gdb) print $rax
$1 = 16
Run Code Online (Sandbox Code Playgroud)
我们应该记住,这numpy/arrayobject.h只是一个定义:
#define PyArray_Check(op) PyObject_TypeCheck(op, &PyArray_Type)
Run Code Online (Sandbox Code Playgroud)
看起来,它PyArray_API以某种方式使用其中一部分 numpy/arrayobject.h未初始化(具有价值init_numpy_api.cpp).
让我们看看MY_PyArray_API预处理器之后(用标志编译use_numpy.h:
static void **PyArray_API= __null
...
static int
_import_array(void)
{
PyArray_API = (void **)PyCapsule_GetPointer(c_api,...
Run Code Online (Sandbox Code Playgroud)
所以extern void **MyPyArray_API我是静态的并且通过初始化Py_Initialize(),这实际上可以解释我在构建期间得到的警告,PyArray_Check已经定义但未使用 - 我们没有初始化&PyArray_Type.
因为它PyArray_API是一个静态变量,所以必须在每个编译单元中初始化,即cpp-file.
所以我们只需要这样做 - 0似乎是官方的方式.