pybind / pybind/pybind11

segmentation fault when shared library callback

Open
#3,579 2 comments 0 reactions 0 assignees View on GitHub

Nobody has claimed this yet.

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

Description

Required prerequisites
Problem description

Hi,
I have a C++ shared library with .so and inculde files, these include files define callback class and virtual function:

struct MyData
{
    char msg[10];
};

class Spi
{
public:
    virtual void OnData(MyData* data) {}
};

I define a trampoline class PySpi , and bind the spi class and the MyData
struct

class PySpi : public Spi {
public:
    using Spi::Spi;

    void OnData(MyData* data) override {
        PYBIND11_OVERRIDE(void, Spi, OnData, data);
    }
};
    py::class_<MyData>(m, "MyData")
        .def(py::init<>())
        .def_property("msg", 
            py::cpp_function([](MyData &self) {return self.msg;}, py::return_value_policy::copy),
            py::cpp_function([](MyData &self, std::string &a) {std::strcpy(self.msg, a.c_str());})
        );

    py::class_<Spi, PySpi>(m, "Spi")
        .def(py::init<>())
        .def("OnData", &Spi::OnData);

overriding virtual function in Python:

class MySpi(Spi):
    def __init__(self):
        Spi.__init__(self)
    def OnData(self, data):
        print("[OnData]")

I am getting a segmentation fault when shared library callback OnData. I tried to change struct return_value_policy, but it didn't work, Am I simply need some policies config of binding?

Reproducible example code

No response

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

No repository file or test is named. Start by reproducing the shared-library callback with the C++ trampoline and Python subclass shown in the issue, then trace the OnData binding and callback path. Done means the segmentation fault is reproduced, its cause is identified, and a verified fix or clear diagnosis is documented.

Written by the indexing model from the issue text.

Assessment

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