pybind / pybind/pybind11

Embedded python: Pass an C++ object by reference

Open
#1,536 5 comments 1 reaction 0 assignees View on GitHub

Nobody has claimed this yet.

Dominant language
C++
Stars
18k
Forks
2.3k
Avg merge
5d 17h
Merged PRs (30d)
10

Description

I have a use-case where I have implemented an API in python and that needs to be invoked by C++.

struct ABC {
ABC(int _i, int _j) {
i = _i;
j = _j;
}
int i;
int j;
};

struct listABC {
listABC() {}
std::string name_;
std::vector lst_;
};

PYBIND11_MAKE_OPAQUE(std::vector);
PYBIND11_MODULE(cc11binds, m) {
py::class
(m, "ABC")
.def(py::init<double, double>())
;
py::class_(m, "listABC")
.def_readwrite("name", &listABC::name_)
.def_readwrite("lst", &listABC::lst_)
;
py::bind_vector<std::vector>(m, "ABCTest", py::module_local(false));
}

struct listABC { std::string name_; std::vector lst_; };

cumabc(&abcList) -> this takes reference to vector object. This works fine:

before cumabc, in C++ --- 2
[i:1 :: j:2]
after cumabc, in C++ --- 2
[i:1 :: j:2, i:3 :: j:4]
Where (3,4) is added by python interpreter.

cumlistABC(&listAbcWrapper) -> This takes reference to listABC object.

My code encounters both the type of pass by reference. Both listAbcWrapper and abcList are passed by class A to B. I was curious if we need to manage the reference count of listAbcWrapper and abcList (i.e. increase the reference count till their lifetime in A. A can later call a freelistAbc and freeCumAbc).
My architecture is:
|-----------------| |------------------| |--------------------|
| Main Driver A | --> | C++ Wrapper B | -----> | Python Callee C |
|-----------------| |------------------| |--------------------|

Contributor guide

Open the contributing guide

First steps

  1. Read the whole issue, then the project's contributing guide.
  2. Comment on the issue to say you are picking it up — it saves two people doing the same work.
  3. Fork the repository and make your change on a branch.
  4. Open a pull request that references the issue number.

Research direction

Start at the PYBIND11_MODULE example and compare the py::class_ and py::bind_vector entry points in the reported A→B→C architecture. Establish the lifetime and reference-count expectations for listABC and vector, with the issue's C++ output serving as the behavior to verify.

Written by the indexing model from the issue text.

Assessment

Tech stack
cpp, python
Domain
backend-api-design, devtools
Issue type
Feature
Difficulty
4/5
Estimated time
3-5 days
Activity status
Stale
Clarity
Needs clarification
Newbie friendliness
25/100

Get new issues in your inbox

A short digest of beginner-friendly GitHub issues.