我坚持this point of the hello world tutorial of boost.Python,我添加了教程要求的内容,编译完共享库后我得到了一个臭名昭着的ImportError
:
1 >>> import hello
---------------------------------------------------------------------------
ImportError Traceback (most recent call last)
<ipython-input-1-f2ff2800b3ef> in <module>()
----> 1 import hello
ImportError: ./hello.so: undefined symbol: _ZN3Num3setEf
2 >>>
我编译了这段代码:
#include <boost/python/module.hpp>
#include <boost/python/def.hpp>
#include <boost/python.hpp>
using namespace boost::python;
struct World
{
World(std::string msg): msg(msg)
{
} // constructor anadido...
void set(std::string msg)
{
this->msg = msg;
}
std::string greet()
{
return msg;
}
std::string msg;
};
struct Var
{
Var(std::string name): name(name), value() {}
std::string const name;
float value;
};
struct Num
{
Num();
float get() const;
void set(float value);
};
BOOST_PYTHON_MODULE(hello)
{
class_<World>("World", init<std::string>())
.def("greet", &World::greet)
.def("set", &World::set)
;
class_<Var>("Var", init<std::string>())
.def_readonly("name", &Var::name)
.def_readwrite("value", &Var::value)
;
class_<Num>("Num")
.add_property("rovalue", &Num::get)
.add_property("value", &Num::get, &Num::set)
;
}
这是我的Jamroot
文件:
# Copyright David Abrahams 2006. Distributed under the Boost
# Software License, Version 1.0. (See accompanying
# file LICENSE_1_0.txt or copy at http://www.boost.org/LICENSE_1_0.txt)
import python ;
if ! [ python.configured ]
{
ECHO "notice: no Python configured in user-config.jam" ;
ECHO "notice: will use default configuration" ;
using python ;
}
# Specify the path to the Boost project. If you move this project,
# adjust this path to refer to the Boost root directory.
use-project boost
: . ;
# Set up the project-wide requirements that everything uses the
# boost_python library from the project whose global ID is
# /boost/python.
project
: requirements <library>/usr/lib/libboost_python.so ;
# Declare the three extension modules. You can specify multiple
# source files after the colon separated by spaces.
python-extension hello : hello.cpp ;
# Put the extension and Boost.Python DLL in the current directory, so
# that running script by hand works.
install convenient_copy
: hello
: <install-dependencies>on <install-type>SHARED_LIB <install-type>PYTHON_EXTENSION
<location>.
;
如果我评论struct Num
及其对Boost.Python的定义,一切都按预期工作。
1 >>> import hello
2 >>> hello.
hello.Var hello.World hello.cpp hello.so
2 >>> x = hello.Var("prueba")
3 >>> x.name
3 <<< 'prueba'
4 >>> x.value = 900
5 >>> x
5 <<< <hello.Var at 0x13245d0>
6 >>> x.value
6 <<< 900.0
7 >>> type(x.value)
7 <<< float
8 >>> exit
jorge [~/coders/desarrollo/practicas/boost] ~>
有任何帮助吗? :)
P.D:我不是C ++经验丰富的程序员! :(
答案 0 :(得分:1)
错误表明您的Num::set
成员函数未定义。如果您将Num
结构更改为:
struct Num
{
Num():internal_value(){}
float get() const
{
return internal_value;
}
void set(float value)
{
internal_value=value;
}
private:
float internal_value;
};
它应该有用。