C++ 和 Python - 检查 PyObject 的类型失败

标签 c++ python pyobject

我有点困惑。我正在尝试进行一些 C++ 和 Python 集成,但它并不那么简单。我没有使用 Boost,因为我无法正确编译 Boost::Python。但这是另一个故事了。

目前,这是我在 C++ 中所做的事情:

//set everything up
PyObject* py_main_module = PyImport_AddModule("__main__");
PyObject* py_global_dict = PyModule_GetDict(py_main_module);
PyObject* py_local_dict = PyDict_New();
PyObject* py_return_value;

PyRun_SimpleString(data.c_str()); //runs Python code, which defines functions

//call a function defined by the python code
py_return_value = PyRun_String("test()", Py_single_input, py_global_dict, py_local_dict);

//attempt to check the type of the returned value
if(py_return_value != NULL) {
    //this is the problem: all of these print 0
    cout << PyList_Check(py_return_value) << endl;
    cout << PySet_Check(py_return_value) << endl;
    cout << PyFloat_Check(py_return_value) << endl;
} else {
    cout << "IT WAS NULL?!" << endl;
}

Python 程序(作为名为“data”的字符串输入到 C++ 程序):

def test():
    derp = 1.234
    #derp = [1, 2, 3, 4]
    #derp = set([1, 2, 3, 4])
    return derp

现在的问题是类型检查不起作用。无论 Python 函数返回的是 float 、列表还是集合,它们都返回 0。我做错了什么?

如果有人能告诉我为什么调用 PyRun_String 会在控制台中打印返回值,那就加分了。实在是太烦人了。

最佳答案

来自the docs :

int Py_eval_input

The start symbol from the Python grammar for isolated expressions; for use with Py_CompileString().

int Py_file_input

The start symbol from the Python grammar for sequences of statements as read from a file or other source; for use with Py_CompileString(). This is the symbol to use when compiling arbitrarily long Python source code.

int Py_single_input

The start symbol from the Python grammar for a single statement; for use with Py_CompileString(). This is the symbol used for the interactive interpreter loop.

Py_single_input 将字符串计算为语句。语句本质上不会返回任何内容,因此您将从 PyRun_String 返回 None。使用 Py_eval_input 来将字符串计算为表达式并获取结果。

关于C++ 和 Python - 检查 PyObject 的类型失败,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/15083720/

相关文章:

c++ - 游戏模式中更新方法的参数

python - 如何获取 distutils 用于构建的 arch 字符串?

python - 在 pytest.ini 中设置不同的测试路径

c++ - 如何在 Python 中处理来自 C++ 的 PyObject*

c++ - 类型的类型与模板?

c++ - 如何执行一个简单的查询使用 sqlapi++ 与 oracle

c# - WMI ConnectServer 到 ROOT\CIMV2 为 C++ 应用程序返回 'Access Denied' 但对于 C# 应用程序工作正常

python - 以顺时针/逆时针方式对二维欧几里德点的复杂集合进行排序以形成一个闭合环

python - 使用来自 C++、PyObject 的参数创建 Python 构造函数