3

I'm trying to use pybind11 to bind heavy computing in C++ with python as front end (unfortunately). I need to pass string/bytes around from python to C++ and back. After reading through the documentation, I thought that "without conversion" meaning that the memory address of C++ and python should be the same when passing around, they are looking at the same data. Here is the dummy code:

In c++:

void string_fn(std::string& x) {
    std::cout << "c++ value is:  " << x << std::endl;
    std::cout << "c++ address is: " << &x << std::endl;
}

PYBIND11_MODULE(module_name, module_handle) {
  module_handle.def("string_fn", &string_fn, py::return_value_policy::reference);
}

Pass data from python:

a = "test_string" # same output with a = b"test_string"
print("python address: ", hex(id(a)))

# call c++ function
string_fn(a)

Outputs are:

python address:  0x7f268c65f240
c++ value is:  test_string
c++ address is: 0x7ffff24c1830

As we can see, the value is the same but the address is different. I'm a total noob and my questions are:

  1. Am I printing the right thing? Or pybind11 just create a copy of python string?
  2. If I'm doing it wrong, how should I achieve it with zero copy?
6
  • 1
    I do not understand how the title is related to the question Commented Jul 18, 2023 at 7:34
  • I guess "without conversion" mentioned in "Passing bytes to C++" means that python will not convert py::bytes to py::str. About pythonic id being the same as transformed argument to c++ function - I don't see anywhere any mentions about it. Commented Jul 18, 2023 at 7:37
  • "string/bytes" String or bytes? These are totally different things. Commented Jul 18, 2023 at 7:42
  • Hi guys, I'm sorry for the confusion. I'm just trying to pass data from python to c++ without it making a copy. Following the docs, I thought that "without conversion" meant that c++ and python should point to the same data, with no need to convert to c++ type. Is there anywhere in the doc I should look into to achieve this? Commented Jul 18, 2023 at 8:22
  • stackoverflow.com/questions/57990269/… Commented Jul 18, 2023 at 11:04

0

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.