自己的字符串用法

时间:2011-05-31 20:07:43

标签: c++ python boost export

我有own string class,我想将它导出到python(使用boost.python)并用作本机字符串。我为此写了转换器。

第一个是导出我的字符串:

bp::class_<CL_StringRef8>("CL_StringRef8", bp::init<const std::string&>())
    .def("CStr", &CL_StringRef8::c_str);

转换器来自默认教程,但我的类型为:

// CL_StringRef8 → Python string --------------------------------------
struct cl_stringref8_to_python_str
{
    static PyObject* convert(CL_StringRef8 const& s)
    {
        return boost::python::incref(boost::python::object(s.c_str()).ptr());
    }
};

// Python string → CL_StringRef8 --------------------------------------
struct cl_stringref8_from_python_str
{
    cl_stringref8_from_python_str()
    {
        bp::converter::registry::push_back(
            &convertible,
            &construct,
            boost::python::type_id<CL_StringRef8>()
        );
    }

    static void* convertible(PyObject* obj_ptr)
    {
        if (!PyString_Check(obj_ptr)) return 0;
        return obj_ptr;
    }

    static void construct(PyObject* obj_ptr, bp::converter::rvalue_from_python_stage1_data* data)
    {
        const char* value = PyString_AsString(obj_ptr);
        if (value == 0) bp::throw_error_already_set();
        void* storage = ((bp::converter::rvalue_from_python_storage<CL_StringRef8>*)data)->storage.bytes;
        new (storage) CL_StringRef8(value);
        data->convertible = storage;
    }
};

现在,据我所知,我可以从python调用c ++函数,它接受参数CL_StringRef8,但我有一个代码:

print GetMyStringObject()
data = float(GetMyStringObject())

# ==>

<CL_StringRef object at 0x7fd15dfd9de8>
TypeError: float() argument must be a string or a number

据我了解,我必须为str()导出CL_StringRef8方法,但我不能这样做:

bp::class_<CL_StringRef8>("CL_StringRef8", bp::init<const std::string&>())
    .def("CStr", &CL_StringRef8::c_str)
    .def(bp::self_ns::str(bp::self_ns::self)); 

最后一行调用错误:

/usr/include/boost/lexical_cast.hpp: In member function ‘bool boost::detail::lexical_stream<Target, Source, Traits>::operator<<(const Source&) [with Target = std::basic_string<char>, Source = CL_StringRef8, Traits = std::char_traits<char>]’:
/usr/include/boost/lexical_cast.hpp:1151:13:   instantiated from ‘Target boost::detail::lexical_cast(typename boost::call_traits<Source>::param_type, CharT*, std::size_t) [with Target = std::basic_string<char>, Source = CL_StringRef8, bool Unlimited = true, CharT = char, typename boost::call_traits<Source>::param_type = const CL_StringRef8&, std::size_t = long unsigned int]’
/usr/include/boost/lexical_cast.hpp:1174:77:   instantiated from ‘Target boost::lexical_cast(const Source&) [with Target = std::basic_string<char>, Source = CL_StringRef8]’
/usr/include/boost/python/operators.hpp:357:1:   instantiated from ‘static PyObject* boost::python::detail::operator_1<(boost::python::detail::operator_id)19u>::apply<T>::execute(boost::python::detail::operator_1<(boost::python::detail::operator_id)19u>::apply<T>::self_t&) [with T = CL_StringRef8, PyObject = _object, boost::python::detail::operator_1<(boost::python::detail::operator_id)19u>::apply<T>::self_t = CL_StringRef8]’
/usr/include/boost/python/operators.hpp:152:11:   instantiated from ‘void boost::python::detail::operator_<id, L, R>::visit(ClassT&) const [with ClassT = boost::python::class_<CL_StringRef8>, boost::python::detail::operator_id id = (boost::python::detail::operator_id)19u, L = boost::python::detail::not_specified, R = boost::python::detail::not_specified]’
/usr/include/boost/python/def_visitor.hpp:31:9:   instantiated from ‘static void boost::python::def_visitor_access::visit(const V&, classT&) [with V = boost::python::def_visitor<boost::python::detail::operator_<(boost::python::detail::operator_id)19u> >, classT = boost::python::class_<CL_StringRef8>]’
/usr/include/boost/python/def_visitor.hpp:67:9:   instantiated from ‘void boost::python::def_visitor<DerivedVisitor>::visit(classT&) const [with classT = boost::python::class_<CL_StringRef8>, DerivedVisitor = boost::python::detail::operator_<(boost::python::detail::operator_id)19u>]’
/usr/include/boost/python/class.hpp:225:9:   instantiated from ‘boost::python::class_<T, X1, X2, X3>::self& boost::python::class_<T, X1, X2, X3>::def(const boost::python::def_visitor<Derived>&) [with Derived = boost::python::detail::operator_<(boost::python::detail::operator_id)19u>, W = CL_StringRef8, X1 = boost::python::detail::not_specified, X2 = boost::python::detail::not_specified, X3 = boost::python::detail::not_specified, boost::python::class_<T, X1, X2, X3>::self = boost::python::class_<CL_StringRef8>]’
/home/ockonal/Workspace/Themisto/src/Scripts/Core/TypesConverters.cpp:375:49:   instantiated from here
/usr/include/boost/lexical_cast.hpp:595:48: error: cannot bind ‘std::basic_ostream<char>’ lvalue to ‘std::basic_ostream<char>&&’
/usr/lib/gcc/x86_64-unknown-linux-gnu/4.6.0/../../../../include/c++/4.6.0/ostream:581:5: error:   initializing argument 1 of ‘std::basic_ostream<_CharT, _Traits>& std::operator<<(std::basic_ostream<_CharT, _Traits>&&, const _Tp&) [with _CharT = char, _Traits = std::char_traits<char>, _Tp = CL_StringRef8]’

ps ,是的,我没有忘记将我的转换器注册到python中。

1 个答案:

答案 0 :(得分:2)

为了使.def(bp::self_ns::str(bp::self_ns::self));行有效,您需要为您的班级定义流媒体运营商。

std::ostream & operator<<(std::ostream & os, const CL_StringRef8 &s)
{ os << s.c_str(); return os; } 

在不需要流操作符的情况下定义str()方法的另一种方法是:

.def("__str__", &CL_StringRef8::c_str) 

虽然,我更喜欢只使用repr()方法,然后在需要时由str()使用

.def("__repr__", &CL_StringRef8::c_str)  

所有这些仍然不会使float()在Python中工作,因为它需要一个字符串(不是一个对象,即使它支持__str__),一个浮点数或一个支持__float__的对象。

我们可以通过在c_str()方法周围绑定lexical_cast来实现后者:

#include <boost/lexical_cast.hpp>
#include <boost/mpl/vector.hpp>  

然后

.def("__float__", bp::make_function( 
                    boost::bind(&boost::lexical_cast<float,CL_StringRef8>,_1),
                      bp::default_call_policies(), 
                        boost::mpl::vector<float,CL_StringRef8>()));

现在你可以用Python做到这一点:

>>> a = CL_StringRef8("1.234")
>>> print a
1.234
>>> float(a) * 2
2.468