我正在使用Python 3.2和C++。檢查PyObjects C類型
我需要提取當前存儲在PyObject中的什麼類型的C類型。 我已經檢查了文檔並搜索了它,似乎沒有其他人需要這樣做。
所以我有一個PyObject,並試圖提取C值。我有需要從對象中實際提取值的函數列表,但我首先需要知道的是正在存儲在對象本身中以調用正確的函數。
爲了以防萬一這有助於理解這裏是我正在嘗試的一些示例代碼。
//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;
}
希望我可以有東西,看起來有點像這個
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;
}
很抱歉,如果這個問題是長期或過多的信息。第一次發佈,不想留下任何可能有幫助的東西。 感謝您對此問題給予的任何幫助或見解。
是的,我的意思是PyInt。 – DaneEC117 2011-05-23 23:00:41
這似乎是迄今爲止我必須嘗試的最佳選擇。我「可能」遇到了一些類型衝突,因爲python並沒有存儲我需要的所有類型,所以我很可能會結合檢查C++函數期望的類型來執行此操作。 – DaneEC117 2011-05-23 23:08:16
你正在編寫一個C++函數的Python包裝器嗎?聽起來你正在重新發明SWIG。 – Adam 2011-05-23 23:11:13