Take the 2-minute tour ×
Stack Overflow is a question and answer site for professional and enthusiast programmers. It's 100% free, no registration required.

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?

share|improve this question
    
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? –  jogojapan Jan 12 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()). –  Mateusz Grzejek Jan 12 at 13:36
add comment

Your Answer

 
discard

By posting your answer, you agree to the privacy policy and terms of service.

Browse other questions tagged or ask your own question.