gpt4 book ai didi

c++ - import_array() 在将 python 和 numpy 嵌入到 C++ 时出错

转载 作者:行者123 更新时间:2023-12-01 14:59:01 34 4
gpt4 key购买 nike

我写了一个简单的代码,试图在 C++ 中使用 numpy。
我的操作系统是 ubuntu16.04 , 与 gcc5.4.0 , Python2.7.12numpy1.15.0 .
这是我的代码 test2.cpp :

#include "Python.h"
#include "numpy/arrayobject.h"

int main(int argc, char **argv)
{
Py_Initialize();
import_array();

Py_Finalize();
return 0;
}

我用的是 CMakeLists.txt像这样:
cmake_minimum_required(VERSION 3.10) 

project(test_python LANGUAGES CXX)

set(CMAKE_CXX_STANDARD 11)
set(CMAKE_BUILD_TYPE DEBUG)

set(PYTHON_INCLUDE_PATH /usr/include/python2.7)
set(PYTHON_LIBRARY /usr/lib/python2.7/config-x86_64-linux-gnu/libpython2.7.so)
set(NUMPY_INCLUDE_PATH /usr/local/lib/python2.7/dist-packages/numpy/core/include)

include_directories(${PYTHON_INCLUDE_PATH})
include_directories(${NUMPY_INCLUDE_PATH})

add_executable(test_python test2.cpp)
target_link_libraries(test_python
${PYTHON_LIBRARY}
)

但是当我成功时,我提出了以下编译错误:
/usr/local/lib/python2.7/dist-packages/numpy/core/include/numpy/__multiarray_api.h:1547:144: error: return-statement with no value, in function returning ‘int’ [-fpermissive]
#define import_array() {if (_import_array() < 0) {PyErr_Print(); PyErr_SetString(PyExc_ImportError, "numpy.core.multiarray failed to import"); return NUMPY_IMPORT_ARRAY_RETVAL; } }
^
/home/camsys/projects/hmr_c/test/test2.cpp:7:5: note: in expansion of macro ‘import_array’
import_array();
^

这很奇怪,因为当我使用 Python3.5 时与 Numpy1.15.0 , 一切都好。 谁能告诉我为什么会发生这个错误以及如何解决它 ?

我发现 4 年前提出的另一个类似问题没有答案 Passing C++ array to python .这个问题是关于 python3.4 , 而我正在处理 python2.7 .

最佳答案

import_array()是在 /usr/local/lib/pythonX.Y/dist-packages/numpy/core/include/numpy/__multiarray_api.h 中定义的宏.在代码预处理期间(编译前),这个宏的定义在main中被扩展和替换。功能就像这样:

int main(int argc, char **argv) 
{
Py_Initialize();
{
if (_import_array() < 0) {
PyErr_Print();
PyErr_SetString(PyExc_ImportError, "numpy.core.multiarray failed to import");
return NUMPY_IMPORT_ARRAY_RETVAL;
}
}
Py_Finalize();
return 0;
}

现在, NUMPY_IMPORT_ARRAY_RETVAL也是在同一个文件中定义的宏 __multiarray_api.h .该宏定义为 NULL对于python3及更高版本,否则什么都没有。
#if PY_VERSION_HEX >= 0x03000000
#define NUMPY_IMPORT_ARRAY_RETVAL NULL
#else
#define NUMPY_IMPORT_ARRAY_RETVAL
#endif
int main函数应该返回一个整数,但在扩展 if statement 中(如果满足条件 _import_array() < 0),则返回 NULL = 0 (#define NULL 0)对于python版本> = 3,因此它有效。对于 python 版本 < 3, main函数不返回任何内容,因此出现错误。

解决方法(对于 Python 版本 < 3):
void temp_func() {
import_array();
}

int main(int argc, char **argv) {
Py_Initialize();
temp_func();

Py_Finalize();
return 0;
}

希望,这回答了这个问题。

关于c++ - import_array() 在将 python 和 numpy 嵌入到 C++ 时出错,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/52074167/

34 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com