pybind / pybind/pybind11

[QUESTION] Seg fault when returning list of tuples containing object and double.

Open
#3,002 0 comments 0 reactions 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

Hi, I am new to pybind11 and relatively new to c++. I have a problem with the code below. I am trying to return a list of tuples containing a python object and a double but for some reason I get a segmentation fault when I run it in python. I have tried to find some hints in the documentation but couldn't find anything relevant to my problem.

Any idea as to why this is happening?

#include <pybind11/pybind11.h>
#include <pybind11/stl.h>

using namespace pybind11::literals;

pybind11::list test(std::vector<std::tuple<pybind11::object*, double>> l) {

    int ls = l.size();
    pybind11::list out;

    for (int i=0; i<ls; i++){

            pybind11::object* ID_0_ptr = std::get<0>(l[i]);
            double x = std::get<1>(l[i]);

            pybind11::tuple t = pybind11::make_tuple(ID_0_ptr, x);

            out.append(t);
    }

    return out;

};

PYBIND11_MODULE(test_module, m) {
    m.def("test", &test);
}
from bson.objectid import ObjectId
import test_module

l = [(ObjectId(), 0.0), (ObjectId(), 1.0), (ObjectId(), 2.0)]
out = test_module.test(l)

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 test() in the C++ snippet and reproduce the Python call with the shown ObjectId tuples. Inspect how the tuple elements are converted and compare the pointer passed to make_tuple with the intended Python object. Done means the call returns a list of tuples without a segmentation fault, preserving each ObjectId and double.

Written by the indexing model from the issue text.

Assessment

Tech stack
cpp, python
Domain
backend-api-design
Issue type
Bug
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.