Jonathon Simister
Jonathon Simister

Reputation: 23

How to pass C++ function as callback to Python?

I am using the Python 3 C API to interface with some Python code.

I have instantiated a Python object from C++ using PyObject_Call and I have been able to modify some of its attributes using PyObject_SetAttrString. One the attributes I would like to modify is a callback function, how can I instantiate a Python object from one of my C++ functions?

Upvotes: 1

Views: 630

Answers (1)

zvone
zvone

Reputation: 19332

What you need to do is to create a Python object which is callable, and when it is called, it ends up calling a function implemented in C (or C++).

I would implement a new class, as specified in Python Type Objects docs. It may implement any kind of constructor etc. you may need, but most importantly for this purpose, it should implement the tp_call, which will make instances of this class callable (as if there was a __call__ method implemented in Python).

The implementation of tp_call is in C/C++ and you can create instances of this class, which are Python objects and can be passed to any Python code.

See also: Defining Extension Types: Tutorial

Upvotes: 1

Related Questions