pybind11 绑定输入输出参数

发布于 2025-01-11 13:54:06 字数 522 浏览 1 评论 0原文

我的 C++ 代码

void test(std::string & data) {
    data += " github";
}

PYBIND11_MODULE(example11, m) {
    m.def("test", [](std::reference_wrapper<std::string> w) {
test(w.get());
    });
}

我的 python 代码

import example11

def my_test():
    data = "hello"
    example11.test(data)
    print("python: {}".format(data))

if __name__ == '__main__':
    my_test()

我期望的是我得到了 hello github,但是得到了 hello,亲爱的朋友们,我的代码有问题吗?

my C++ code

void test(std::string & data) {
    data += " github";
}

PYBIND11_MODULE(example11, m) {
    m.def("test", [](std::reference_wrapper<std::string> w) {
test(w.get());
    });
}

my python code

import example11

def my_test():
    data = "hello"
    example11.test(data)
    print("python: {}".format(data))

if __name__ == '__main__':
    my_test()

what i expect is i got hello github, however hello is gotten, is there something wrong in my code, dear guys?

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(1

夏尔 2025-01-18 13:54:06

您不能在Python中使用输出参数,请参阅 官方文档。只有可变类型(str 除外)可以就地更改。即使对于可变类型,由于 pybind11

要解决您的问题,请返回修改后的值。

std::string test(std::string & data) {
    data += " github";
    return data;
}

PYBIND11_MODULE(example11, m) {
    m.def("test", &test);
}

在Python调用中

data = example11.test(data)

You can't use output parameter in Python, see detailed explaination in the official doc. Only mutable types(str exclued) can be changed in-place. Even for mutable types, you still can't get modified result since the restriction of pybind11.

To fix your issue, return the modified value.

std::string test(std::string & data) {
    data += " github";
    return data;
}

PYBIND11_MODULE(example11, m) {
    m.def("test", &test);
}

in Python call

data = example11.test(data)
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文