Extending and Embedding Python in C++: Is PyImport_AddModule required to import extension module before importing python script?
Asked Answered
P

0

6

I am embedding Python in a C++ application and I also need to call back in to the C++ code from Python. I have been able to do this with the following simple example but I'm having a weird problem in my C++ application.

Module definitions...

static PyObject*
say_hello(PyObject* self, PyObject* args)
{
    const char* name;

    if (!PyArg_ParseTuple(args, "s", &name))
        return NULL;

    printf("Hello %s!\n", name);

    Py_RETURN_NONE;
}

static  PyMethodDef HelloMethods[] =
{
    { "say_hello", say_hello, METH_VARARGS, "Greet somebody." },
    { NULL, NULL, 0, NULL }
};

static struct PyModuleDef hellomodule = {
    PyModuleDef_HEAD_INIT,
    "hello",
    NULL,
    -1,
    HelloMethods
};

PyMODINIT_FUNC
PyInit_hello(void)
{
    return PyModule_Create(&hellomodule);
}

In main()...

PyImport_AppendInittab("hello", &PyInit_hello);

// Initialize Python.
Py_Initialize();
PySys_SetArgv(argc, argv);
CPyObject pmod(PyImport_ImportModule("demo")); //CPyObject is a wrapper class

Python file demo.py...

import hello
hello.say_hello("something")

When I add this code to my C++ application I get a read access violation at PyImport_ImportModule(). To prevent this I included the following line of code before the import.

PyObject * pmod2 = PyImport_AddModule("hello");

This allows me to import a python script which includes "import hello" but I am not able to execute any of the functions in the hello module.

Why is PyImport_AddModule preventing the read access violation?

I'm not an experienced developer so I may be making some very basic mistakes. Any help would be much appreciated.

EDIT

I have overcome the problem by adding the functions also with...

PyModule_AddFunctions(pmod2, HelloMethods);

So although I have already initialised the module, before importing a script which is using this module I need to add it and the functions. I'm not sure I understand why so if someone could rationalise this for me it would be useful.

Pietro answered 26/1, 2017 at 14:21 Comment(1)
Do you check the result from PyImport_AppendInittab? That could indicate an error?Greggs

© 2022 - 2025 — McMap. All rights reserved.