Boost Python:在函数中通过引用传递变量时出错 [英] Boost Python: Error when passing variable by reference in a function

查看:162
本文介绍了Boost Python:在函数中通过引用传递变量时出错的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想了解为什么以下函数在python中不起作用:

I would like to understand why the following function does not work in python:

#include<boost/python.hpp>
#include<iostream>
#include<string>

void hello(std::string& s) {

   std::cout << s << std::endl;
}

BOOST_PYTHON_MODULE(test)
{
   boost::python::def("hello", hello);
}

当我将库导入python

When I import library into python

import test
test.hello('John')

我收到一个错误:

test.hello(str)
did not match C++ signature:
   hello(std::__cxx11::basic_string<char, std::char_traits<char>, std::allocator<char> > {lvalue})

一切都只适用于'std :: string s',但我想通过引用引用该对象而不复制它.我注意到该错误对于其他任何带有参考等功能的函数都会弹出. int&.

Everything works with just 'std::string s', but I would like to the object by reference without copying it. I noticed that the error pops up for any other function with references like e.g. int&.

推荐答案

正如 kindall 所述,python字符串是不可变的.一种解决方案可以是stl :: string包装器.您的python端会受到影响,但这是一个简单的解决方案,并且需要为该接口支付少量费用

As kindall mentioned, python strings are immutable. one solution can be a stl::string wrapper. your python side will be affected, but it's a sipmle solution and a small price to pay for that interface

class_<std::string>("StlString")
        .def(init<std::string>())
        .def_readonly("data", &std::string::data);

请注意,将 assign 运算符python转换为c ++ stl将由boost提供,但是您必须公开 data 成员才能访问存储的数据.我为c ++对象的外观添加了另一个构造函数.

note that the assign operator, python to c++ stl will be given by boost, but you'll have to expose the data member in order to access the stored data. Iv'e added another costructor for the look and feel of c++ object.

>>> import test
>>> stlstr = test.StlString()
>>> stlstr
<test.StlString object at 0x7f1f0cda74c8>
>>> stlstr.data
''
>>> stlstr = 'John'
>>> stlstr.data
'John'
>>> initstr = test.StlString('John')
>>> initstr.data
'John'

这篇关于Boost Python:在函数中通过引用传递变量时出错的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆