PyObject* init_local_module(PyObject *m) { PyObject *d, *sd, *v; PyObject *sys_modules, *module; PyMethodDef *ml; #ifdef PY3 PyObject *mod_name = PyUnicode_FromString(MODULE_NAME "." LOCAL_MOD_NAME); #else PyObject *mod_name = PyBytes_FromString(MODULE_NAME "." LOCAL_MOD_NAME); #endif if(mod_name == NULL){ return NULL; } LocalObjectType.tp_new = PyType_GenericNew; if(PyType_Ready(&LocalObjectType) < 0){ return NULL; } sys_modules = PySys_GetObject("modules"); d = PyModule_GetDict(m); module = PyDict_GetItem(d, mod_name); if(module == NULL) { module = PyModule_New(MODULE_NAME "." LOCAL_MOD_NAME); if(module != NULL) { PyDict_SetItem(sys_modules, mod_name, module); PyModule_AddObject(m, LOCAL_MOD_NAME, module); } } sd = PyModule_GetDict(module); for(ml = LocalMod_methods; ml->ml_name != NULL; ml++){ v = PyCFunction_NewEx(ml, (PyObject *)NULL, mod_name); if(v == NULL) { goto fin; } if(PyDict_SetItemString(sd, ml->ml_name, v) != 0){ Py_DECREF(v); return NULL; } Py_DECREF(v); } fin: Py_DECREF(mod_name); Py_INCREF(&LocalObjectType); PyModule_AddObject(module, "local", (PyObject *)&LocalObjectType); #ifdef PY3 dict_key = PyUnicode_FromString("_jega_local_dict__"); #else dict_key = PyBytes_FromString("_jega_local_dict__"); #endif return module; }
static PyObject * new_module(PyObject* unused, PyObject* args) { char *name; if (!PyArg_ParseTuple(args, "s:module", &name)) return NULL; return PyModule_New(name); }
static PyObject* create_module(char *name, PyObject *co) { PyObject *m; PyObject *d; PyObject *v; PyObject *err; assert(name); assert(co); /*创建一个新的模块*/ m = PyModule_New(name); if(m == NULL) { Ps_Log("create new module failed\n", Ps_LOG_WARING); return NULL; } /*初始化这个新的模块*/ d = PyModule_GetDict(m); if(PyDict_SetItemString(d, "__builtins__", PyEval_GetBuiltins()) != 0) { Ps_Log("Set new module builtin failed\n", Ps_LOG_WARING); PyErr_SetString(PyExc_ImportError, "Cannot get builtin dict"); goto error; } v= ((PyCodeObject*)co)->co_filename; Py_INCREF(v); if(PyDict_SetItemString(d, "__file__", v) != 0) PyErr_Clear(); Py_DECREF(v); #ifdef IMPORT_DEBUG Ps_Log("$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$\n", Ps_LOG_NORMAL); //Ps_LogObject(d, Ps_LOG_NORMAL); Ps_Log("$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$\n", Ps_LOG_NORMAL); #endif /*执行字节码*/ v = PyEval_EvalCode((PyCodeObject*)co, d, d); if(v == NULL || (err = PyErr_Occurred())) { Ps_LogObject(d, Ps_LOG_WARING); Ps_Log("PyEval_EvalCode failed\n", Ps_LOG_WARING); return NULL; //goto error; } Py_XDECREF(v); Py_INCREF(m); return m; error: Py_DECREF(m); return NULL; }
/***************************************************************************** * Description: This function creates a new Python dictionary object. * note: dict is owned by sys.modules["__main__"] module, reference is borrowed * note: important we use the dict from __main__, this is what python expects for 'pickle' to work as well as strings like this... >> foo = 10 >> print(__import__("__main__").foo) * * note: this overwrites __main__ which gives problems with nested calles. * be sure to run PyC_MainModule_Backup & PyC_MainModule_Restore if there is * any chance that python is in the call stack. *****************************************************************************/ PyObject *PyC_DefaultNameSpace(const char *filename) { PyInterpreterState *interp= PyThreadState_GET()->interp; PyObject *mod_main= PyModule_New("__main__"); PyDict_SetItemString(interp->modules, "__main__", mod_main); Py_DECREF(mod_main); /* sys.modules owns now */ PyModule_AddStringConstant(mod_main, "__name__", "__main__"); if(filename) PyModule_AddStringConstant(mod_main, "__file__", filename); /* __file__ only for nice UI'ness */ PyModule_AddObject(mod_main, "__builtins__", interp->builtins); Py_INCREF(interp->builtins); /* AddObject steals a reference */ return PyModule_GetDict(mod_main); }
ElementDocumentWrapper::ElementDocumentWrapper(PyObject* self, const char* tag) : ElementWrapper< ElementDocument >(self, tag) { Rocket::Core::String module_id(32, "document_%x", this); // Create a new module module = PyModule_New(module_id.CString()); module_namespace = PyModule_GetDict(module); // Merging main into the module PyObject* builtins = PyImport_AddModule("__main__"); PyObject* builtins_dict = PyModule_GetDict( builtins); PyDict_Merge(module_namespace, builtins_dict, 0); }
/* Load a script manually using PyRun_File. * This expects a null terminated array of strings * (such as from g_strsplit) of the command line. * The array needs at least one item */ static int py_load_script_path_argv(const char *path, char **argv) { PyObject *module = NULL, *script = NULL; char *name = NULL; name = file_get_filename(path); module = PyModule_New(name); g_free(name); if (!module) goto error; script = pyscript_new(module, argv); Py_DECREF(module); if (!script) goto error; /* insert script obj into module dict, load file */ if (PyModule_AddObject(module, "_script", script) != 0) goto error; Py_INCREF(script); if (!py_load_module(module, path)) goto error; if (PyList_Append(script_modules, script) != 0) goto error; printtext(NULL, NULL, MSGLEVEL_CLIENTERROR, "loaded script %s", argv[0]); /* PySys_WriteStdout("load %s, script -> 0x%x\n", argv[0], script); */ Py_DECREF(script); return 1; error: if (PyErr_Occurred()) PyErr_Print(); printtext(NULL, NULL, MSGLEVEL_CLIENTERROR, "error loading script %s", argv[0]); if (script) { /* make sure to clean up any formats, signals, commands that may have been attached before the exception took place */ pyscript_cleanup(script); Py_DECREF(script); } return 0; }
/* returns borrowed reference */ _DLL_EXPORT PyObject *getJavaModule(PyObject *module, const char *parent, const char *name) { PyObject *modules = PyImport_GetModuleDict(); PyObject *parent_module, *full_name; if (parent[0] == '\0') { parent_module = NULL; full_name = PyString_FromString(name); } else if ((parent_module = PyDict_GetItemString(modules, parent)) == NULL) { PyErr_Format(PyExc_ValueError, "Parent module '%s' not found", parent); return NULL; } else full_name = PyString_FromFormat("%s.%s", parent, name); PyObject *child_module = PyDict_GetItem(modules, full_name); if (child_module == NULL) { child_module = PyModule_New(PyString_AS_STRING(full_name)); if (child_module != NULL) { if (parent_module != NULL) PyDict_SetItemString(PyModule_GetDict(parent_module), name, child_module); PyDict_SetItem(modules, full_name, child_module); Py_DECREF(child_module); /* borrow reference */ } } Py_DECREF(full_name); /* During __install__ pass, __file__ is not yet set on module. * During __initialize__ pass, __file__ is passed down to child_module. */ if (child_module != NULL) { PyObject *__file__ = PyString_FromString("__file__"); PyObject *file = PyDict_GetItem(PyModule_GetDict(module), __file__); if (file != NULL) PyDict_SetItem(PyModule_GetDict(child_module), __file__, file); Py_DECREF(__file__); } return child_module; }
PyObject * PyImport_AddModule(char *name) { LOG("> PyImport_AddModule\n"); { PyObject *modules = PyImport_GetModuleDict(); PyObject *m; if ((m = PyDict_GetItemString(modules, name)) != NULL && PyModule_Check(m)) return m; m = PyModule_New(name); if (m == NULL) return NULL; if (PyDict_SetItemString(modules, name, m) != 0) { Py_DECREF(m); return NULL; } Py_DECREF(m); LOG("< PyImport_AddModule\n"); return m; }}
static PyObject * create_newmodule(char *name) { PyObject *mod, *moddict; mod = PyModule_New(name); if (mod == NULL) return NULL; /* Register into module dict to allow such codes like: * from freebsd.const import * */ moddict = PyImport_GetModuleDict(); if (moddict == NULL) { Py_DECREF(mod); return NULL; } PyDict_SetItemString(moddict, name, mod); return mod; }
/***************************************************************************** * Description: Creates the bpy module and adds it to sys.modules for importing *****************************************************************************/ void BPy_init_modules(void) { extern BPy_StructRNA *bpy_context_module; extern int bpy_lib_init(PyObject *); PointerRNA ctx_ptr; PyObject *mod; /* Needs to be first since this dir is needed for future modules */ char *modpath= BLI_get_folder(BLENDER_SYSTEM_SCRIPTS, "modules"); if (modpath) { // printf("bpy: found module path '%s'.\n", modpath); PyObject *sys_path= PySys_GetObject("path"); /* borrow */ PyObject *py_modpath= PyUnicode_FromString(modpath); PyList_Insert(sys_path, 0, py_modpath); /* add first */ Py_DECREF(py_modpath); } else { printf("bpy: couldnt find 'scripts/modules', blender probably wont start.\n"); } /* stand alone utility modules not related to blender directly */ IDProp_Init_Types(); /* not actually a submodule, just types */ mod= PyModule_New("_bpy"); /* add the module so we can import it */ PyDict_SetItemString(PyImport_GetModuleDict(), "_bpy", mod); Py_DECREF(mod); /* run first, initializes rna types */ BPY_rna_init(); PyModule_AddObject(mod, "types", BPY_rna_types()); /* needs to be first so bpy_types can run */ PyModule_AddObject(mod, "StructMetaPropGroup", (PyObject *)&pyrna_struct_meta_idprop_Type); /* metaclass for idprop types, bpy_types.py needs access */ bpy_lib_init(mod); /* adds '_bpy._library_load', must be called before 'bpy_types' which uses it */ bpy_import_test("bpy_types"); PyModule_AddObject(mod, "data", BPY_rna_module()); /* imports bpy_types by running this */ bpy_import_test("bpy_types"); PyModule_AddObject(mod, "props", BPY_rna_props()); PyModule_AddObject(mod, "ops", BPY_operator_module()); /* ops is now a python module that does the conversion from SOME_OT_foo -> some.foo */ PyModule_AddObject(mod, "app", BPY_app_struct()); /* bpy context */ RNA_pointer_create(NULL, &RNA_Context, (void *)BPy_GetContext(), &ctx_ptr); bpy_context_module= (BPy_StructRNA *)pyrna_struct_CreatePyObject(&ctx_ptr); /* odd that this is needed, 1 ref on creation and another for the module * but without we get a crash on exit */ Py_INCREF(bpy_context_module); PyModule_AddObject(mod, "context", (PyObject *)bpy_context_module); /* utility func's that have nowhere else to go */ PyModule_AddObject(mod, meth_bpy_script_paths.ml_name, (PyObject *)PyCFunction_New(&meth_bpy_script_paths, NULL)); PyModule_AddObject(mod, meth_bpy_blend_paths.ml_name, (PyObject *)PyCFunction_New(&meth_bpy_blend_paths, NULL)); PyModule_AddObject(mod, meth_bpy_user_resource.ml_name, (PyObject *)PyCFunction_New(&meth_bpy_user_resource, NULL)); PyModule_AddObject(mod, meth_bpy_resource_path.ml_name, (PyObject *)PyCFunction_New(&meth_bpy_resource_path, NULL)); /* register funcs (bpy_rna.c) */ PyModule_AddObject(mod, meth_bpy_register_class.ml_name, (PyObject *)PyCFunction_New(&meth_bpy_register_class, NULL)); PyModule_AddObject(mod, meth_bpy_unregister_class.ml_name, (PyObject *)PyCFunction_New(&meth_bpy_unregister_class, NULL)); /* add our own modules dir, this is a python package */ bpy_package_py= bpy_import_test("bpy"); }
PyObject * PyModule_Create2(struct PyModuleDef* module, int module_api_version) { PyObject *d, *v, *n; PyMethodDef *ml; const char* name; PyModuleObject *m; if (!Py_IsInitialized()) Py_FatalError("Interpreter not initialized (version mismatch?)"); if (PyType_Ready(&moduledef_type) < 0) return NULL; if (module->m_base.m_index == 0) { max_module_number++; Py_REFCNT(module) = 1; Py_TYPE(module) = &moduledef_type; module->m_base.m_index = max_module_number; } name = module->m_name; if (module_api_version != PYTHON_API_VERSION) { char message[512]; PyOS_snprintf(message, sizeof(message), api_version_warning, name, PYTHON_API_VERSION, name, module_api_version); if (PyErr_WarnEx(PyExc_RuntimeWarning, message, 1)) return NULL; } /* Make sure name is fully qualified. This is a bit of a hack: when the shared library is loaded, the module name is "package.module", but the module calls PyModule_Create*() with just "module" for the name. The shared library loader squirrels away the true name of the module in _Py_PackageContext, and PyModule_Create*() will substitute this (if the name actually matches). */ if (_Py_PackageContext != NULL) { char *p = strrchr(_Py_PackageContext, '.'); if (p != NULL && strcmp(module->m_name, p+1) == 0) { name = _Py_PackageContext; _Py_PackageContext = NULL; } } if ((m = (PyModuleObject*)PyModule_New(name)) == NULL) return NULL; if (module->m_size > 0) { m->md_state = PyMem_MALLOC(module->m_size); if (!m->md_state) { PyErr_NoMemory(); Py_DECREF(m); return NULL; } memset(m->md_state, 0, module->m_size); } d = PyModule_GetDict((PyObject*)m); if (module->m_methods != NULL) { n = PyUnicode_FromString(name); if (n == NULL) return NULL; for (ml = module->m_methods; ml->ml_name != NULL; ml++) { if ((ml->ml_flags & METH_CLASS) || (ml->ml_flags & METH_STATIC)) { PyErr_SetString(PyExc_ValueError, "module functions cannot set" " METH_CLASS or METH_STATIC"); Py_DECREF(n); return NULL; } v = PyCFunction_NewEx(ml, (PyObject*)m, n); if (v == NULL) { Py_DECREF(n); return NULL; } if (PyDict_SetItemString(d, ml->ml_name, v) != 0) { Py_DECREF(v); Py_DECREF(n); return NULL; } Py_DECREF(v); } Py_DECREF(n); } if (module->m_doc != NULL) { v = PyUnicode_FromString(module->m_doc); if (v == NULL || PyDict_SetItemString(d, "__doc__", v) != 0) { Py_XDECREF(v); return NULL; } Py_DECREF(v); } m->md_def = module; return (PyObject*)m; }
PyObject* init_locks_module(PyObject *m) { PyObject *d, *sd, *v; PyObject *sys_modules, *module; PyMethodDef *ml; #ifdef PY3 PyObject *mod_name = PyUnicode_FromString(MODULE_NAME "." LOCKS_MOD_NAME); #else PyObject *mod_name = PyBytes_FromString(MODULE_NAME "." LOCKS_MOD_NAME); #endif if(mod_name == NULL){ return NULL; } sys_modules = PySys_GetObject("modules"); d = PyModule_GetDict(m); module = PyDict_GetItem(d, mod_name); if(module == NULL) { module = PyModule_New(MODULE_NAME "." LOCKS_MOD_NAME); if(module != NULL) { PyDict_SetItem(sys_modules, mod_name, module); PyModule_AddObject(m, LOCKS_MOD_NAME, module); } } sd = PyModule_GetDict(module); for(ml = LocksMod_methods; ml->ml_name != NULL; ml++){ v = PyCFunction_NewEx(ml, (PyObject *)NULL, mod_name); if(v == NULL) { goto fin; } if(PyDict_SetItemString(sd, ml->ml_name, v) != 0){ Py_DECREF(v); return NULL; } Py_DECREF(v); } fin: Py_DECREF(mod_name); SemaphoreObjectType.tp_new = PyType_GenericNew; if(PyType_Ready(&SemaphoreObjectType) < 0){ return NULL; } BoundedSemaphoreObjectType.tp_new = PyType_GenericNew; if(PyType_Ready(&BoundedSemaphoreObjectType) < 0){ return NULL; } LockObjectType.tp_new = PyType_GenericNew; if(PyType_Ready(&LockObjectType) < 0){ return NULL; } RLockObjectType.tp_new = PyType_GenericNew; if(PyType_Ready(&RLockObjectType) < 0){ return NULL; } ConditionObjectType.tp_new = PyType_GenericNew; if(PyType_Ready(&ConditionObjectType) < 0){ return NULL; } Py_INCREF(&SemaphoreObjectType); PyModule_AddObject(module, "Semaphore", (PyObject *)&SemaphoreObjectType); Py_INCREF(&BoundedSemaphoreObjectType); PyModule_AddObject(module, "BoundedSemaphore", (PyObject *)&BoundedSemaphoreObjectType); Py_INCREF(&LockObjectType); PyModule_AddObject(module, "Lock", (PyObject *)&LockObjectType); Py_INCREF(&RLockObjectType); PyModule_AddObject(module, "RLock", (PyObject *)&RLockObjectType); Py_INCREF(&ConditionObjectType); PyModule_AddObject(module, "Condition", (PyObject *)&ConditionObjectType); return module; }
void Master::pyRegisterAllClasses(){ LOG_DEBUG("called with "<<modulePluginClasses.size()<<" module+class pairs."); std::map<std::string,py::object> pyModules; py::object wooScope=boost::python::import("woo"); auto synthesizePyModule=[&](const string& modName){ py::object m(py::handle<>(PyModule_New(("woo."+modName).c_str()))); m.attr("__file__")="<synthetic>"; wooScope.attr(modName.c_str())=m; pyModules[modName.c_str()]=m; // http://stackoverflow.com/questions/11063243/synethsized-submodule-from-a-import-b-ok-vs-import-a-b-error/11063494 py::extract<py::dict>(py::getattr(py::import("sys"),"modules"))()[("woo."+modName).c_str()]=m; LOG_DEBUG_EARLY("Synthesized new module woo."<<modName); }; // this module is synthesized for core.Master; other synthetic modules are created on-demand in the loop below synthesizePyModule("core"); py::scope core(py::import("woo.core")); this->pyRegisterClass(); woo::ClassTrait::pyRegisterClass(); woo::AttrTraitBase::pyRegisterClass(); woo::TimingDeltas::pyRegisterClass(); Object().pyRegisterClass(); // virtual method, therefore cannot be static // http://boost.2283326.n4.nabble.com/C-sig-How-to-create-package-structure-in-single-extension-module-td2697292.html list<pair<string,shared_ptr<Object>>> pythonables; for(const auto& moduleName: modulePluginClasses){ string module(moduleName.first); string name(moduleName.second); shared_ptr<Object> obj; try { LOG_DEBUG("Factoring class "<<name); obj=factorClass(name); assert(obj); // needed for Master::childClasses for(int i=0;i<obj->getBaseClassNumber();i++) classBases[name].insert(obj->getBaseClassName(i)); // needed for properly initialized class indices Indexable* indexable=dynamic_cast<Indexable*>(obj.get()); if(indexable) indexable->createIndex(); // if(pyModules.find(module)==pyModules.end()){ try{ // module existing as file, use it pyModules[module]=py::import(("woo."+module).c_str()); } catch (py::error_already_set& e){ // PyErr_Print shows error and clears error indicator if(getenv("WOO_DEBUG")) PyErr_Print(); // this only clears the the error indicator else PyErr_Clear(); synthesizePyModule(module); } } pythonables.push_back(make_pair(module,obj)); } catch (std::runtime_error& e){ /* FIXME: this catches all errors! Some of them are not harmful, however: * when a class is not factorable, it is OK to skip it; */ cerr<<"Caught non-critical error for class "<<module<<"."<<name; } } // handle Object specially // py::scope _scope(pyModules["core"]); // Object().pyRegisterClass(pyModules["core"]); /* python classes must be registered such that base classes come before derived ones; for now, just loop until we succeed; proper solution will be to build graphs of classes and traverse it from the top. It will be done once all classes are pythonable. */ for(int i=0; i<11 && pythonables.size()>0; i++){ if(i==10) throw std::runtime_error("Too many attempts to register python classes. Run again with WOO_DEBUG=1 to get better diagnostics."); LOG_DEBUG_EARLY_FRAGMENT(endl<<"[[[ Round "<<i<<" ]]]: "); std::list<string> done; for(auto I=pythonables.begin(); I!=pythonables.end(); ){ const std::string& module=I->first; const shared_ptr<Object>& s=I->second; const std::string& klass=s->getClassName(); try{ LOG_DEBUG_EARLY_FRAGMENT("{{"<<klass<<"}}"); py::scope _scope(pyModules[module]); s->pyRegisterClass(); auto prev=I++; pythonables.erase(prev); } catch (...){ LOG_DEBUG_EARLY("["<<klass<<"]"); if(getenv("WOO_DEBUG")) PyErr_Print(); else PyErr_Clear(); I++; } } } }
void initPyTypes(void) { /* initPyObjectPlusType(BL_ActionActuator::Parents); ..... */ /* For now just do PyType_Ready */ PyObject *mod= PyModule_New("GameTypes"); PyObject *dict= PyModule_GetDict(mod); PyDict_SetItemString(PySys_GetObject((char *)"modules"), (char *)"GameTypes", mod); Py_DECREF(mod); for(int init_getset= 1; init_getset > -1; init_getset--) { /* run twice, once to init the getsets another to run PyType_Ready */ PyType_Ready_Attr(dict, BL_ActionActuator, init_getset); PyType_Ready_Attr(dict, BL_Shader, init_getset); PyType_Ready_Attr(dict, BL_ShapeActionActuator, init_getset); PyType_Ready_Attr(dict, BL_ArmatureObject, init_getset); PyType_Ready_Attr(dict, BL_ArmatureActuator, init_getset); PyType_Ready_Attr(dict, BL_ArmatureConstraint, init_getset); PyType_Ready_AttrPtr(dict, BL_ArmatureBone, init_getset); PyType_Ready_AttrPtr(dict, BL_ArmatureChannel, init_getset); PyType_Ready_Attr(dict, CListValue, init_getset); PyType_Ready_Attr(dict, CValue, init_getset); PyType_Ready_Attr(dict, KX_BlenderMaterial, init_getset); PyType_Ready_Attr(dict, KX_Camera, init_getset); PyType_Ready_Attr(dict, KX_CameraActuator, init_getset); PyType_Ready_Attr(dict, KX_ConstraintActuator, init_getset); PyType_Ready_Attr(dict, KX_ConstraintWrapper, init_getset); PyType_Ready_Attr(dict, KX_GameActuator, init_getset); PyType_Ready_Attr(dict, KX_GameObject, init_getset); PyType_Ready_Attr(dict, KX_IpoActuator, init_getset); PyType_Ready_Attr(dict, KX_LightObject, init_getset); PyType_Ready_Attr(dict, KX_FontObject, init_getset); PyType_Ready_Attr(dict, KX_MeshProxy, init_getset); PyType_Ready_Attr(dict, KX_MouseFocusSensor, init_getset); PyType_Ready_Attr(dict, KX_NearSensor, init_getset); PyType_Ready_Attr(dict, KX_NetworkMessageActuator, init_getset); PyType_Ready_Attr(dict, KX_NetworkMessageSensor, init_getset); PyType_Ready_Attr(dict, KX_ObjectActuator, init_getset); PyType_Ready_Attr(dict, KX_ParentActuator, init_getset); PyType_Ready_Attr(dict, KX_PhysicsObjectWrapper, init_getset); PyType_Ready_Attr(dict, KX_PolyProxy, init_getset); PyType_Ready_Attr(dict, KX_PolygonMaterial, init_getset); PyType_Ready_Attr(dict, KX_RadarSensor, init_getset); PyType_Ready_Attr(dict, KX_RaySensor, init_getset); PyType_Ready_Attr(dict, KX_SCA_AddObjectActuator, init_getset); PyType_Ready_Attr(dict, KX_SCA_DynamicActuator, init_getset); PyType_Ready_Attr(dict, KX_SCA_EndObjectActuator, init_getset); PyType_Ready_Attr(dict, KX_SCA_ReplaceMeshActuator, init_getset); PyType_Ready_Attr(dict, KX_Scene, init_getset); PyType_Ready_Attr(dict, KX_NavMeshObject, init_getset); PyType_Ready_Attr(dict, KX_SceneActuator, init_getset); PyType_Ready_Attr(dict, KX_SoundActuator, init_getset); PyType_Ready_Attr(dict, KX_StateActuator, init_getset); PyType_Ready_Attr(dict, KX_SteeringActuator, init_getset); PyType_Ready_Attr(dict, KX_TouchSensor, init_getset); PyType_Ready_Attr(dict, KX_TrackToActuator, init_getset); PyType_Ready_Attr(dict, KX_VehicleWrapper, init_getset); PyType_Ready_Attr(dict, KX_VertexProxy, init_getset); PyType_Ready_Attr(dict, KX_VisibilityActuator, init_getset); PyType_Ready_Attr(dict, PyObjectPlus, init_getset); PyType_Ready_Attr(dict, SCA_2DFilterActuator, init_getset); PyType_Ready_Attr(dict, SCA_ANDController, init_getset); PyType_Ready_Attr(dict, SCA_ActuatorSensor, init_getset); PyType_Ready_Attr(dict, SCA_AlwaysSensor, init_getset); PyType_Ready_Attr(dict, SCA_DelaySensor, init_getset); PyType_Ready_Attr(dict, SCA_ILogicBrick, init_getset); PyType_Ready_Attr(dict, SCA_IObject, init_getset); PyType_Ready_Attr(dict, SCA_ISensor, init_getset); PyType_Ready_Attr(dict, SCA_JoystickSensor, init_getset); PyType_Ready_Attr(dict, SCA_KeyboardSensor, init_getset); PyType_Ready_Attr(dict, SCA_MouseSensor, init_getset); PyType_Ready_Attr(dict, SCA_NANDController, init_getset); PyType_Ready_Attr(dict, SCA_NORController, init_getset); PyType_Ready_Attr(dict, SCA_ORController, init_getset); PyType_Ready_Attr(dict, SCA_PropertyActuator, init_getset); PyType_Ready_Attr(dict, SCA_PropertySensor, init_getset); PyType_Ready_Attr(dict, SCA_PythonController, init_getset); PyType_Ready_Attr(dict, SCA_RandomActuator, init_getset); PyType_Ready_Attr(dict, SCA_RandomSensor, init_getset); PyType_Ready_Attr(dict, SCA_XNORController, init_getset); PyType_Ready_Attr(dict, SCA_XORController, init_getset); PyType_Ready_Attr(dict, SCA_IController, init_getset); PyType_Ready_Attr(dict, SCA_PythonKeyboard, init_getset); PyType_Ready_Attr(dict, SCA_PythonMouse, init_getset); } /* Normal python type */ PyType_Ready(&KX_PythonSeq_Type); #ifdef USE_MATHUTILS /* Init mathutils callbacks */ KX_GameObject_Mathutils_Callback_Init(); KX_ObjectActuator_Mathutils_Callback_Init(); #endif }
/* * PyPgFunction_load_module - create and load the module * * This execute the module body in a new module object iff the module does not * already exist in sys.modules. * * The PL protocol checks are not done here because this could be called from * the code of another function. It's the caller's responsibility to ensure that * the appropriate checks are being made at the appropriate time. */ PyObj PyPgFunction_load_module(PyObj func) { PyObj modules, module, modname, d, code, evalr; int rv; Assert(func != NULL); Assert(PyPgFunction_Check(func)); modules = PyImport_GetModuleDict(); rv = PySequence_Contains(modules, PyPgFunction_GetPyUnicodeOid(func)); if (rv == -1) return(NULL); else if (rv == 1) { /* * If this returns NULL, it's probably some weird race condition... * The check above said it exists, so let's trust it. */ return(PyObject_GetItem(modules, PyPgFunction_GetPyUnicodeOid(func))); } /* * Hasn't been loaded into sys.modules yet. */ code = PyPgFunction_get_code(func); if (code == NULL) return(NULL); modname = PyPgFunction_GetPyUnicodeOid(func); Py_INCREF(modname); PyObject_StrBytes(&modname); if (modname == NULL) { Py_DECREF(code); return(NULL); } module = PyModule_New(PyBytes_AS_STRING(modname)); Py_DECREF(modname); if (module == NULL) { Py_DECREF(code); return(NULL); } d = PyModule_GetDict(module); if (PyDict_SetItemString(d, "__builtins__", Py_builtins_module) != 0) goto fail; /* * __loader__ PEP302 support. * This is what linecache uses to access the function's source */ if (PyDict_SetItemString(d, "__loader__", func) != 0) goto fail; if (PyDict_SetItemString(d, "__func__", func) != 0) goto fail; if (PyDict_SetItemString(d, "__file__", PyPgFunction_GetFilename(func)) != 0) goto fail; /* * Module has to exist in sys.modules before code evaluates. */ if (PyObject_SetItem(modules, PyPgFunction_GetPyUnicodeOid(func), module) != 0) goto fail; /* * Module context, therefore locals and globals are the same object. */ evalr = PyEval_EvalCode((PyCodeObject *) code, d, d); if (evalr == NULL) { /* * Code evaluation failed. Remove the junk module from sys.modules. */ PyObject_DelItem(modules, PyPgFunction_GetPyUnicodeOid(func)); goto fail; } Py_DECREF(evalr); Py_DECREF(code); return(module); fail: Py_DECREF(code); Py_DECREF(module); return(NULL); }
static PyObject* createfunc_unreported_exception(PyObject *spec, PyModuleDef *def) { PyErr_SetString(PyExc_SystemError, "bad create function"); return PyModule_New("foo"); }
PyObject * PyModule_Create2(struct PyModuleDef* module, int module_api_version) { const char* name; PyModuleObject *m; PyInterpreterState *interp = PyThreadState_Get()->interp; if (interp->modules == NULL) Py_FatalError("Python import machinery not initialized"); if (!PyModuleDef_Init(module)) return NULL; name = module->m_name; if (!check_api_version(name, module_api_version)) { return NULL; } if (module->m_slots) { PyErr_Format( PyExc_SystemError, "module %s: PyModule_Create is incompatible with m_slots", name); return NULL; } /* Make sure name is fully qualified. This is a bit of a hack: when the shared library is loaded, the module name is "package.module", but the module calls PyModule_Create*() with just "module" for the name. The shared library loader squirrels away the true name of the module in _Py_PackageContext, and PyModule_Create*() will substitute this (if the name actually matches). */ if (_Py_PackageContext != NULL) { const char *p = strrchr(_Py_PackageContext, '.'); if (p != NULL && strcmp(module->m_name, p+1) == 0) { name = _Py_PackageContext; _Py_PackageContext = NULL; } } if ((m = (PyModuleObject*)PyModule_New(name)) == NULL) return NULL; if (module->m_size > 0) { m->md_state = PyMem_MALLOC(module->m_size); if (!m->md_state) { PyErr_NoMemory(); Py_DECREF(m); return NULL; } memset(m->md_state, 0, module->m_size); } if (module->m_methods != NULL) { if (PyModule_AddFunctions((PyObject *) m, module->m_methods) != 0) { Py_DECREF(m); return NULL; } } if (module->m_doc != NULL) { if (PyModule_SetDocString((PyObject *) m, module->m_doc) != 0) { Py_DECREF(m); return NULL; } } m->md_def = module; return (PyObject*)m; }
PyObject * PyModule_Create2(struct PyModuleDef* module, int module_api_version) { PyObject *d, *v, *n; PyMethodDef *ml; const char* name; PyModuleObject *m; PyInterpreterState *interp = PyThreadState_Get()->interp; if (interp->modules == NULL) Py_FatalError("Python import machinery not initialized"); if (PyType_Ready(&moduledef_type) < 0) return NULL; if (module->m_base.m_index == 0) { max_module_number++; Py_REFCNT(module) = 1; Py_TYPE(module) = &moduledef_type; module->m_base.m_index = max_module_number; } name = module->m_name; if (module_api_version != PYTHON_API_VERSION && module_api_version != PYTHON_ABI_VERSION) { int err; err = PyErr_WarnFormat(PyExc_RuntimeWarning, 1, "Python C API version mismatch for module %.100s: " "This Python has API version %d, module %.100s has version %d.", name, PYTHON_API_VERSION, name, module_api_version); if (err) return NULL; } /* Make sure name is fully qualified. This is a bit of a hack: when the shared library is loaded, the module name is "package.module", but the module calls PyModule_Create*() with just "module" for the name. The shared library loader squirrels away the true name of the module in _Py_PackageContext, and PyModule_Create*() will substitute this (if the name actually matches). */ if (_Py_PackageContext != NULL) { char *p = strrchr(_Py_PackageContext, '.'); if (p != NULL && strcmp(module->m_name, p+1) == 0) { name = _Py_PackageContext; _Py_PackageContext = NULL; } } if ((m = (PyModuleObject*)PyModule_New(name)) == NULL) return NULL; if (module->m_size > 0) { m->md_state = PyMem_MALLOC(module->m_size); if (!m->md_state) { PyErr_NoMemory(); Py_DECREF(m); return NULL; } memset(m->md_state, 0, module->m_size); } d = PyModule_GetDict((PyObject*)m); if (module->m_methods != NULL) { n = PyUnicode_FromString(name); if (n == NULL) { Py_DECREF(m); return NULL; } for (ml = module->m_methods; ml->ml_name != NULL; ml++) { if ((ml->ml_flags & METH_CLASS) || (ml->ml_flags & METH_STATIC)) { PyErr_SetString(PyExc_ValueError, "module functions cannot set" " METH_CLASS or METH_STATIC"); Py_DECREF(n); Py_DECREF(m); return NULL; } v = PyCFunction_NewEx(ml, (PyObject*)m, n); if (v == NULL) { Py_DECREF(n); Py_DECREF(m); return NULL; } if (PyDict_SetItemString(d, ml->ml_name, v) != 0) { Py_DECREF(v); Py_DECREF(n); Py_DECREF(m); return NULL; } Py_DECREF(v); } Py_DECREF(n); } if (module->m_doc != NULL) { _Py_IDENTIFIER(__doc__); v = PyUnicode_FromString(module->m_doc); if (v == NULL || _PyDict_SetItemId(d, &PyId___doc__, v) != 0) { Py_XDECREF(v); Py_DECREF(m); return NULL; } Py_DECREF(v); } m->md_def = module; return (PyObject*)m; }