I have code for the Python interface in C ++ that works fine, but every time I look at it, I think there should be a better way to do this. On the C ++ side, there is a type βvariantβ, which can deal with a fixed range of basic types - int, real, string, vector variants, etc. I have some code that uses the Python API to convert from equivalent Python types. It looks something like this:
variant makeVariant(PyObject* value) { if (PyString_Check(value)) { return PyString_AsString(value); } else if (value == Py_None) { return variant(); } else if (PyBool_Check(value)) { return value == Py_True; } else if (PyInt_Check(value)) { return PyInt_AsLong(value); } else if (PyFloat_Check(value)) { return PyFloat_AsDouble(value); }
The problem is chained if-else ifs. It seems to be called for a switch statement or a table or map of creation functions that is associated with a type identifier. In other words, I want to write something like:
return createFunMap[typeID(value)](value);
Based on viewing the API docs, it was not obvious that the best way to get the βtypeIDβ here is. I see that I can do something like this:
PyTypeObject* type = value->ob_type;
This seems to quickly change type information, but what is the cleanest way to use this to communicate with a limited set of types that interest me?
c python python-c-extension python-c-api
Bob
source share