当我尝试通过boost::numpy::ndarray作为参数时,我得到了我认为是奇怪的段错误:
I am getting what I think is a strange seg fault when I am trying to pass boost::numpy::ndarray as an argument:
#include <iostream> #include <boost/python.hpp> #include <boost/numpy.hpp> void say_hello(boost::numpy::ndarray& my_array) //void say_hello(int x) This works fine { std::cout<<"Hello"<<std::endl; } BOOST_PYTHON_MODULE(hello_ext) { using namespace boost::python; def("say_hello", say_hello); }我知道这个例子很愚蠢,但是我不应该在那儿遇到段错误,这是我能够减少问题的最小例子.也许我需要指定ndarray类型或尺寸数,但是找不到关于它的任何文档.我当时在看此,但是看起来不是很乐于助人.我的直觉是我缺少一些简单的东西,但是我看不到它.
I know the example is silly, but I should not be getting a seg fault there, and this is the smallest example I was able to reduce the problem to. Maybe I need to specify the ndarray type or number of dimensions, but I could not find any documentation on it. I was looking at this, but it didn't seem very helpful. My gut feeling is I am missing something simple, but I just don't see it.
运行此命令时:
In [1]: from hello_ext import * In [2]: import numpy as np In [3]: say_hello(np.array([3,4,5])) Segmentation fault (core dumped)我的Makefile:
My Makefile:
PYTHON_VERSION = 2.7 PYTHON_INCLUDE = /usr/include/python$(PYTHON_VERSION) BOOST_INC = /usr/include BOOST_LIB = /usr/lib TARGET = hello_ext $(TARGET).so: $(TARGET).o g++ -std=c++11 -shared -Wl,--export-dynamic $(TARGET).o -L$(BOOST_LIB) -lboost_python -lboost_numpy -L/usr/lib/python$(PYTHON_VERSION)/config -lpython$(PYTHON_VERSION) -o $(TARGET).so $(TARGET).o: $(TARGET).cpp g++ -std=c++11 -I$(PYTHON_INCLUDE) -I$(BOOST_INC) -fPIC -c $(TARGET).cp推荐答案
我知道这很简单.我需要添加这两行:
I knew it was something simple. I needed to add these two lines:
Py_Initialize(); boost::numpy::initialize();如所解释的:此处如果未运行上述行,则在尝试使用boost::numpy::ndarray后都会出现段错误.
as explained : here seg fault results after any attempt to use boost::numpy::ndarray if the above lines are not ran.
因此:我的文件变为:
#include <iostream> #include <boost/python.hpp> #include <boost/numpy.hpp> void say_hello(boost::numpy::ndarray& my_array) //void say_hello(int x) This works fine { std::cout<<"Hello"<<std::endl; } BOOST_PYTHON_MODULE(hello_ext) { using namespace boost::python; Py_Initialize(); boost::numpy::initialize(); def("say_hello", say_hello); }更多推荐
使用boost :: numpy :: ndarray时出现分段错误
发布评论