0

I try to write C-extension which contains python class.

This class takes a filename as a parameter fname of constructor, then loads that file to memory and stores as a config.

Below what I have:

typedef struct {
    PyObject_HEAD
    XmlConfig m_cfg;
} PyAgent;

static int PyAgent_init(PyAgent *self, PyObject *args) {
    const char *fname;
    if (!PyArg_ParseTuple(args, "s", &fname)) {
    return NULL;
    }
    self->m_cfg.Load(fname);
    return 0;
}

static PyTypeObject PyAgentType = {
   PyObject_HEAD_INIT(NULL)
   0,                                            /* ob_size */
   "classify.Agent",                             /* tp_name */
   ...
}
...

I get segmentation fault when I try to load file. As I understand it happens because PyAgent struct has object size that increases because of memory allocation for file.

I've tried to use PyObject_VAR_HEAD macro but it doesn't help.

Can you give a clue or working similar example?

user3666197
  • 1
  • 6
  • 50
  • 92
San4ez
  • 8,091
  • 4
  • 41
  • 62

1 Answers1

1

Maybe self->m_cfg needs to be initialized first? You are calling a C++ method on it, but didn't call its constructor first. The struct is allocated by C code, not C++, so it doesn't know it needs to construct this field.

There are ways to manually call the constructor (something like new(&self->m_cfg) XmlConfig() if I remember correctly), but the easiest is probably to have instead a field XmlConfig *cfg, and allocate and free it as needed with the usual syntax of the C++ operators new and delete (the latter to be put in the tp_dealloc).

Armin Rigo
  • 12,048
  • 37
  • 48