python - 在 C++ 中嵌入 python 并提取 C++ 类型
问题描述
我正在尝试在我的 c++ 程序中嵌入简单的 python 指令。我无法从 python 对象类型中提取 c++ 类型...不胜感激!
示例程序:
#include <iostream>
#include <Python.h>
using namespace std;
int main()
{
Py_Initialize();
auto pModule = PyImport_ImportModule("math");
auto pFunc = PyObject_GetAttrString(pModule, "sin");
auto pIn = Py_BuildValue("(f)", 2.);
auto pRes = PyObject_CallObject(pFunc, pIn);
auto cRes = ???;
cout << cRes << endl;
Py_Finalize();
}
程序应该简单地打印 sin(2) 的结果。
解决方案
你会想知道函数调用的类型,包括错误......如果函数引发异常,则PyObject_CallObject
应该返回 NULL,所以首先检查一下:
if (!pRes) {
PyErr_Print();
// don't do anything else with pRes
}
否则,您可以检查并解释您可能期望从 Python 函数调用中获得的每种类型:
if (pRes == Py_None) {
cout << "result is None" << endl;
} else if (PyFloat_Check(pRes)) {
auto cRes = PyFloat_AsDouble(pRes);
cout << cRes << endl;
} else if (<other checks>) {
// Handle other types
} else {
cout << "Unexpected return type" << endl;
}
在您math.sin()
调用的情况下,您可能可以安全地假设异常或 PyFloat 返回。