gpt4 book ai didi

python - 在 Boost Python 中使用带有 std::wstring 的 C++ 函数的 Unicode

转载 作者:太空狗 更新时间:2023-10-29 21:42:44 25 4
gpt4 key购买 nike

我正在使用 Boost Python 库来包装我拥有的 C++ 类,以便我可以从 Python 调用它的方法。我的 C++ 类 Clazz 有公共(public)方法:

void doSomething(std::string& s) { ... }
void doSomethingWide(std::wstring& ws) { ... }

我创建了一个指向这两个方法的 BOOST_PYTHON_MODULE。第一个使用 std::string 我可以正常调用。但是,当我尝试使用 Python Unicode 字符串调用第二个时:

x = u'hello'
Clazz.doSomethingWide(x)

我得到错误:

ArgumentError: Python 参数类型
Clazz.doSomethingWide(Clazz,unicode)
不匹配 C++ 签名:
doSomething(Clazz, std::wstring)

我曾希望 unicode 会自动与 std::wstring 交互,就像常规 Python 字符串类型与 std::string 交互一样。然而,情况似乎并非如此。

在另一个线程中,有人建议先进行转换:

x = str(x.encode('utf-8'))

但是,我正在处理非常大的字符串,这破坏了我的代码的性能,因为它是 O(n) x 的字符数。

确实能够修改我尝试与之交互的 C++ 库。有没有办法以我可以使用它们的方式将 Python unicode 类型传递到我的 C++ 库中?我在 Internet 上广泛搜索并找到了一些对转换器和其他东西的引用,但是实现它们并没有修复上面的错误消息(很可能我没有正确使用它们)。

最佳答案

简而言之,类型转换通常会产生右值对象,因此参数必须按值接受或按常量引用接受。因此,改变:

void doSomethingWide(std::wstring&);

以下任一项:

void doSomethingWide(std::wstring);
void doSomethingWide(const std::wstring&);

添加了 Boost.Python std::wstring conversions 2003 年 9 月 11 日。作为一般规则,当在 Boost.Python 中发生类型转换时,生成的对象被视为右值。 boost::python::extract 中间接记录了此行为观察者规范:

Converts the stored pointer to result_type, which is either T or T const&.

如果支持左值转换,它可能会为某些类型引入尴尬的语义。例如,不可变的 Python 字符串可以通过 C++ 函数进行修改。


这是一个完整的最小示例:

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

class spam
{
public:
void doSomething(const std::string& str)
{
std::cout << "spam::doSomething(): " << str << std::endl;
}

void doSomethingWide(const std::wstring& str)
{
std::wcout << "spam::doSomethingWide(): " << str << std::endl;
}
};

BOOST_PYTHON_MODULE(example)
{
namespace python = boost::python;
python::class_<spam>("Spam")
.def("doSomething", &spam::doSomething)
.def("doSomethingWide", &spam::doSomethingWide)
;
}

交互使用:

>>> import example
>>> spam = example.Spam()
>>> spam.doSomething("test")
spam::doSomething(): test
>>> spam.doSomethingWide(u"test")
spam::doSomethingWide(): test

关于python - 在 Boost Python 中使用带有 std::wstring 的 C++ 函数的 Unicode,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/25210858/

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