I am using Python 3.2 and C++.
I need to extract what kind of C type is currently being stored in a PyObject. I have checked over the documentation and googled it as well and no one else seems to have needed to do this.
So I have a PyObject and am attempting to extract the C Value. I have the list of functions need to actually extract the value from the object, but what I need to know first is what is being stored in the object itself as to call the correct function.
Just in case this helps understand here is some example code of what I am attempting.
//Variable is a custom variant type to allow for generic functionality.
Variable ExtractArgument( PyObject * arg )
{
Variable value;
PyObject* result;
//now here is the problem, I need to know which Python function to call in order to
//extract the correct type;
value = PyLong_FromLong( arg );
//or
value = PyFloat_FromDouble( arg )
//ect.
return value;
}
Hopefully I could have something that looks sort of like this
Variable ExtractArgument( PyObject * arg )
{
Variable value;
PyObject* result;
//PyType is not the actual variable to that holds the type_macro, GetType should be
//replaced by the function I am trying to find
PyType type = GetType( arg );
switch( type )
{
case T_INT: value = static_cast<int>(PyLong_FromLong( arg ));
break;
case T_FLOAT: value = static_cast<float>(PyFloat_FromDouble( arg ));
break;
case T_DOUBLE: value = PyDouble_FromDouble( arg );
break;
//ect.
}
return value;
}
Sorry if this question is to long, or too much info. First time post and didn't want to leave anything out that may help. Thank you for any help or insight you can give me on this issue.
Python objects don't have a C type, they have a Python type. For example, an integer can be an C long or a long integer. You can check for the type with PyInt_Check(obj)
, PyList_Check(obj)
, etc. If that returns true then you know you have an object of that type.
Note that PyLong_FromLong
and such go the other way. They take a C value and turn it into a PyObject*. So you're using them backwards. I think you meant PyInt_AsLong
.