pybind11 bind input output parameter

Viewed 127

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?

1 Answers

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)
Related