pybind / pybind/pybind11

[QUESTION] Implements a pure virtual class in python calls pure virtual function

Open
#2,844 1 comment 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

I am trying to implement a virtual class i have in C++ using Python. To do that, I am using the trampoline as described in pybind documentation. The issue here is that in python, I need to keep the python object around or I would have a pure virtual function call error.

My python class looks like this

class BlendingField(PyVNCS.Sim2D.BlendingField):
    def __init__(self):
        PyVNCS.Sim2D.BlendingField.__init__(self)

    def blending(self, point):
        return 0.5

And I have to use like this

blendingField = BlendingField()
simCreator.blendingField = blendingField

simCreator.create()

Basically, I create the BlendingField with the python implementation, I assign it to simCreator.blendingField property and I call simCreator.create(), which is a C++ function using the blending field.

If instead of doing it like that, I do it like this

simCreator.blendingField = BlendingField()

simCreator.create()

I get a crash when trying to use the blending field from C++. This happens because the python object is destroyed.

Is this the expected behavior? I find it kind of confusing and it needs an extra line which most of the times you dont really want.

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 by reproducing the lifetime behavior with the BlendingField trampoline and the two simCreator.blendingField assignment forms, then inspect how simCreator.create() uses the object. Done means establishing whether the crash is expected and identifying a documented or actionable ownership behavior.

Written by the indexing model from the issue text.

Assessment

Tech stack
cpp, python
Domain
backend-api-design
Issue type
Bug
Difficulty
5/5
Estimated time
Over a week
Activity status
Stale
Clarity
Needs clarification
Newbie friendliness
25/100

Get new issues in your inbox

A short digest of beginner-friendly GitHub issues.