Inheritance in Python C++ extension

2024/10/5 15:33:29

I have c++ library that need communicate with Python plugged in modules. Communication supposes implementing by Python some callback c++ interface.

I have read already about writing extensions, but no idea how to develop inheritance.

So something about: C++:

class Broadcast
{void set(Listener *){...
}class Listener
{void notify(Broadcast* owner) = 0;
}

I need something like in Python:

class ListenerImpl(Listener):...def notify(self, owner):...

Note, I don't want use Boost.

Answer

Since I had to implement single inheritance as part of the Python C-API in a project of mine, I built a short example here. I marked the important statements in the code.

The trick is to inherit the base struct in the top of the subclass struct (leave out the PyObject_HEAD statement).

/* OBJECT */
typedef struct {MyPy_BaseClass super; // <----- PUTTING THIS FIRST INHERITS THE BASE PYTHON CLASS!!!// Own variables:// e.g int x = 0;
} MyPy_InheritanceClass;

Also dont forget to give the base type to the subclass type. There is a flag for it (see /* tp_base */).

  static PyTypeObject MyPy_InheritanceClass_Type = {PyVarObject_HEAD_INIT(NULL, 0)"MyPy_InheritanceClass",          /* tp_name */sizeof(MyPy_InheritanceClass),    /* tp_basicsize */0,                         /* tp_itemsize */(destructor)MyPy_InheritanceClass_dealloc, /* tp_dealloc */0,                         /* tp_print */0,                         /* tp_getattr */0,                         /* tp_setattr */0,                         /* tp_reserved */0,                         /* tp_repr */0,                         /* tp_as_number */0,                         /* tp_as_sequence */0,                         /* tp_as_mapping */0,                         /* tp_hash  */0,                         /* tp_call */0,                         /* tp_str */0,                         /* tp_getattro */0,                         /* tp_setattro */0,                         /* tp_as_buffer */Py_TPFLAGS_DEFAULT |Py_TPFLAGS_BASETYPE,       /* tp_flags */ "MyPy_InheritanceClass",   /* tp_doc */0,                         /* tp_traverse */0,                         /* tp_clear */0,                         /* tp_richcompare */0,                         /* tp_weaklistoffset */0,                         /* tp_iter */0,                         /* tp_iternext */MyPy_InheritanceClass_methods,    /* tp_methods */0,                         /* tp_members */0,                         /* tp_getset */&MyPy_BaseClass_Type,      /* tp_base */ // <------ GIVE THE BASE_CLASS TYPE0,                         /* tp_dict */0,                         /* tp_descr_get */0,                         /* tp_descr_set */0,                         /* tp_dictoffset */(initproc) MyPy_InheritanceClass_init, /* tp_init */0,                         /* tp_alloc */MyPy_InheritanceClass_new, /* tp_new */
};
https://en.xdnf.cn/q/70473.html

Related Q&A

exposing C++ class in Python ( only ET_DYN and ET_EXEC can be loaded)

I was looking at here to see how to expose c++ to Python. I have built Python deep learning code which uses boost-python to connect c++ and python and it is running ok, so my system has things for boos…

Migrations in mongoengine: InvalidId

I am working with mongoengine and trying to do a simple migration. I have a field which I would like to migrate from being a StringField to a ReferenceField to another Object. I planned on doing the …

Keras pretrain CNN with TimeDistributed

Here is my problem, I want to use one of the pretrain CNN network in a TimeDistributed layer. But I have some problem to implement it.Here is my model:def bnn_model(max_len):# sequence length and resne…

How to `pause`, and `resume` download work?

Usually, downloading a file from the server is something like this: fp = open(file, wb) req = urllib2.urlopen(url) for line in req:fp.write(line) fp.close()During downloading, the download process just…

AttributeError: module rest_framework.serializers has no attribute NullBooleanField

After upgrading djangorestframework from djangorestframework==3.13.1 to djangorestframework==3.14.0 the code from rest_framework.serializers import NullBooleanFieldThrowsAttributeError: module rest_fra…

Pandas convert dataframe values to column names

I want to use dataframe values as column names and simplify the dataframe.I tried df.stack() and then index.map({0[0]}_{0[1]}.format)Input_df(Got this df by doing a groupby):link price dateA 1 …

Pandas replace part of string with values from dictionary

I would like to replace the words in my dataframedf = pd.DataFrame({"Text": ["The quick brown fox jumps over the lazy dog"]})which match the keys in the following dictionarydic = {&…

Tensorflow autoencoder cost not decreasing?

I am working on unsupervised feature learning using autoencoders using Tensorflow. I have written following code for the Amazon csv dataset and when I am running it the cost is not decreasing at every …

Seconds since epoch to relative date

Im working with dates since epoch, and already got, for example:date = 6928727.56235Id like to transform this into another relative format, so that Ill be able to transform this into something relative…

ring buffer with numpy/ctypes

Im developing a client which will receive the [EEG] data over tcp and write it to the ring buffer. I thought it can be very convenient to have the buffer as a ctypes or numpy array because its possible…