2

I try to run some Python scripts from inside the C++ code. I reach the point, in which I need to use my custom type. I found article in Python doc about creating custom types and nice SOQ, explaining how to create instances of custom type on C++ side.

I am not sure, however, how am I suppose to use this type in Python. In doc sample, a 'module initializer' is defined:

PyMODINIT_FUNC PyInit_module_type(void) 
{
    CX_type.tp_new = PyType_GenericNew;
    if (PyType_Ready(&CX_type) < 0)
        return NULL;
    //create module, return it
}

But there is no hint what is purpose of this function. How (and when) this function is called?

Currently, I run my scripts either by PyEval_EvalCode() to run whole script or PyObject_Call() to run specific function. How do I use my type in both cases? Do I need to import it first somehow?

If I import my scripts as modules:

PyObject* pm_1 = PyImport_Import("pm_1.py")

do I need to add my type to each module I create this way:

Py_INCREF(&CX_type);
PyModule_AddObject(pm_1, "CX", (PyObject*)&CX_type);

? I think, that types created after Py_Initialize() (so, during single interpreter session) should be visible automatically to all modules imported during this session. Am I wrong?

2
  • Is the PyInit_module_type function all you have defined? For a custom data type there should be much more. You need to define the data type itself and pointers to its constructors, destructors and member functions. Have you defined all that? Commented Jan 12, 2014 at 13:27
  • Yes. I have functions that handle new, init and dealloc, getters/setters and members definition etc. Also the data type struct itself, filled with all required values (CX_type in above code). I do not know, however, how to use it in Python in case of executing single function (PyObject_Call()) and code object (PyEval_EvalCode()). Commented Jan 12, 2014 at 13:36

0

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.