From 33b2c7d353186c24b54389b273cbdb0cf8c27c5f Mon Sep 17 00:00:00 2001 From: marioalexis Date: Wed, 1 Sep 2021 10:10:39 -0300 Subject: [PATCH] Base: Add 'getTypeIfDerivedFrom' member function to Type class --- src/Base/Type.cpp | 13 +++++++++++++ src/Base/Type.h | 2 ++ src/Base/TypePyImp.cpp | 25 ++++++++++++++----------- 3 files changed, 29 insertions(+), 11 deletions(-) diff --git a/src/Base/Type.cpp b/src/Base/Type.cpp index bd39e5cb35..1019f8a3c4 100644 --- a/src/Base/Type.cpp +++ b/src/Base/Type.cpp @@ -234,3 +234,16 @@ int Type::getNumTypes(void) { return typedata.size(); } + +Type Type::getTypeIfDerivedFrom(const char* name , const Type parent, bool bLoadModule) +{ + if (bLoadModule) + importModule(name); + + Type type = fromName(name); + + if (type.isDerivedFrom(parent)) + return type; + else + return Type::badType(); +} diff --git a/src/Base/Type.h b/src/Base/Type.h index f77390cf56..3aab2208e6 100644 --- a/src/Base/Type.h +++ b/src/Base/Type.h @@ -101,6 +101,8 @@ public: bool isDerivedFrom(const Type type) const; static int getAllDerivedFrom(const Type type, std::vector& List); + /// Returns the given named type if is derived from parent type, otherwise return bad type + static Type getTypeIfDerivedFrom(const char* name , const Type parent, bool bLoadModule=false); static int getNumTypes(void); diff --git a/src/Base/TypePyImp.cpp b/src/Base/TypePyImp.cpp index f4ec19b70c..cb100869db 100644 --- a/src/Base/TypePyImp.cpp +++ b/src/Base/TypePyImp.cpp @@ -216,26 +216,29 @@ PyObject* TypePy::createInstance (PyObject *args) if (!PyArg_ParseTuple(args, "")) return nullptr; - Base::BaseClass* base = static_cast(getBaseTypePtr()->createInstance()); - if (!base) { - Py_Return; - } + Py::String name(getBaseTypePtr()->getName()); + Py::TupleN tuple(name); - return createPyObject(base); + return createInstanceByName(tuple.ptr()); } PyObject* TypePy::createInstanceByName (PyObject *args) { - const char* type; + const char* name; PyObject* load = Py_False; - if (!PyArg_ParseTuple(args, "s|O!", &type, &PyBool_Type, &load)) + if (!PyArg_ParseTuple(args, "s|O!", &name, &PyBool_Type, &load)) return nullptr; - Base::BaseClass* base = static_cast - (Base::Type::createInstanceByName(type, PyObject_IsTrue(load) ? true : false)); - if (!base) { + bool bLoad = PyObject_IsTrue(load) ? true : false; + Base::Type type = Base::Type::getTypeIfDerivedFrom(name, Base::BaseClass::getClassTypeId(), bLoad); + if (type.isBad()) Py_Return; - } + + void* typeInstance = type.createInstance(); + if (!typeInstance) + Py_Return; + + Base::BaseClass* base = static_cast(typeInstance); return createPyObject(base); }