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?

1 Answer 1

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).

Sign up to request clarification or add additional context in comments.

1 Comment

Thank you a lot. I've chosen the easiest way with new/delete.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.