0

I'm writing some Python Module using the C extension API. And I want to implement insert() and is_greater() methods. both methods should take an argument of int type or any user-defined object which has implemented __gt__() method. To make it simple, need the interface like below.

mc = MyClass()
mc.insert(1)
isGreater = mc.is_greater(2)
mc = MyClass()
obj1 = MyObject(1)
mc.insert(obj1)
obj2 = MyObject(2)
isGreater = mc.is_greater(obj2)

I'm using the PyArg_ParseTuple function to parse the variable into a raw C Pointer like below.

typedef int(* COMPARE_FUNCP)(PyObject * , PyObject * );

typedef struct
{
    PyObject_HEAD
    PyObject * objp;
    COMPARE_FUNCP * is_greater;
} MyClassObject;

static PyObject * 
myClass_insert(MyClassObject * self, PyObject * args)
{
    PyObject * objp1;
    if (!PyArg_ParseTuple(args, "O", &objp1))
    {
        return NULL;
    }
    self->objp = objp1;
    // here I want to register MyObject class's __gt__() method.
    self->is_greater = 
}

static PyObject * 
myClass_compare(MyClassObject * self, PyObject * args)
{
    PyObject * objp2;
    if (!PyArg_ParseTuple(args, "O", &objp2))
    {
        return NULL;
    }
    if (self->is_greater(self->objp, objp2)>0)
        return Py_True;
}

I guess I need to register __gt__() method in C somehow, but How can I do this?

Someone please give me a clue. Thank you.

agongji
  • 117
  • 1
  • 7
  • 1
    https://stackoverflow.com/questions/29175295/python-compare-objects-in-c-api is very similar (although there isn't a function pointer with the signature you want) – DavidW Dec 12 '22 at 09:24

0 Answers0