简体   繁体   中英

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?

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM