Custom PyObject inheritance in C ++

Long-term python programmer, first C ++ scripting developer. Anyway, for fun, I'm trying to create a linked list module for python in C ++. Here is my code

#include <python2.7/Python.h>
#include <iostream>

using namespace std;

template <typename T>
class LinkedList : public PyObject {
private:
  struct ListNode {
    ListNode(T value, ListNode* next)
      : value(value), next(next) {}
    T value;
    ListNode* next;
  };
  ListNode* head;

public:
  LinkedList(T value)
    : head(new ListNode(value, 0)) {
    cout << "class constructed" << endl;
    Py_INCREF(this);
  }
  void get_value() {
    cout << "test" << endl;
  }
  ~LinkedList() {
    delete head;
    Py_DECREF(this);
    cout << "class destructed" << endl;
  }
};

static PyObject* linkedlist_new(PyObject* self, PyObject* args) {
  LinkedList<char*> ll("hello");
  return Py_BuildValue("O", &ll);
}

static PyMethodDef LinkedListMethods[] = {
    {"new", linkedlist_new, METH_VARARGS,
     "Create a new linked list."},
    {NULL, NULL, 0, NULL}
};

extern "C" PyMODINIT_FUNC initLinkedList(void) {
  (void) Py_InitModule("LinkedList", LinkedListMethods);
}

Can I do it? Most documents are for C, but can I inherit from PyObject and return it like that? What is working now:

import LinkedList

print "start"
l = LinkedList.new()
print "done"

but as soon as I call l.get_value()in python, I get segfault. I know that what I'm doing is probably wrong, so will anyone be so kind as to point me in the right direction?

And for clarification, I know that LinkedList<char*>with the name "ll" it is destroyed after the function is executed linkedlist_new, which is part of the problem that I am facing. Let me just assume that I am very, very lost ...

+4
1

-: - ,

template <typename T>
class LinkedList : public PyObject { /* … */ }

-

template <typename T>
class LinkedList {
    public:
        PyObject_HEAD
        /// …
}

... , API Python . : PyTypeObject, (qv https://docs.python.org/2/c-api/typeobj.html), , .

, PyTypeObject, PyObject, , , PyObject -derived LinkedList , PyTypeObject ( , , ), typename, LinkList .

+3

Source: https://habr.com/ru/post/1619748/


All Articles