I am able to use embedded Python in my MSVS Windows C++ app and it works well. I can create com objects and use them like this:
import win32com.client as win32
Dialogs = win32.Dispatch('DialogControls.Dialogs')
Dialogs.Message(0, "Hello from C++ object")`
I have many objects that are created inside the C++ app and I want to access them and also their event handlers also in Python. Previously I used VBScript and I was able to do this with AddObjectEx but in Python I have no success. I tried something like this but it doesn’t work. pComObject is NULL.
void PythonEng::PassComObjectToPython(const CString& ObjName, IDispatch* pMyComObject) {
Py_Initialize();
PyObject* pModule = PyImport_ImportModule("win32com.client");
if (pModule) {
PyObject* pDict = PyModule_GetDict(pModule);
PyObject* pDispatch = PyDict_GetItemString(pDict, "Dispatch");
if (pDispatch && PyCallable_Check(pDispatch)) {
PyObject* pArgs = PyTuple_Pack(1, PyLong_FromVoidPtr(pMyComObject));
PyObject* pComObject = PyObject_CallObject(pDispatch, pArgs);
Py_DECREF(pArgs);
if (pComObject) {
PyObject* pGlobals = PyDict_New();
CT2CA pszConvertedAnsiString(ObjName);
std::string strObjName(pszConvertedAnsiString);
PyDict_SetItemString(pGlobals, strObjName.c_str(), pComObject);
Py_DECREF(pComObject);
// Now you can execute Python code that uses my_com_object
PyRun_String("MyGen.Idle(10)", Py_file_input, pGlobals, pGlobals);
Py_DECREF(pGlobals);
}
}
Py_DECREF(pModule);
}
Py_Finalize();
}
I tried to add my com object with the above code and use it from embedded Python.