gpt4 book ai didi

c++ - Python NamedTuple 到 C++ 结构

转载 作者:行者123 更新时间:2023-11-30 03:37:10 25 4
gpt4 key购买 nike

此时我已经在互联网上搜索了几个小时。有谁知道如何将从 python 函数返回的 namedtuple 解析为结构或只是解析为单独的变量。我遇到问题的部分是从返回的指针中获取数据。我正在使用 PyObject_CallFunction() 调用调用嵌入在 C++ 中的 python 函数,一旦我拥有返回数据的 PyObject*,我不知道该怎么做。

我正在使用 Python 2.7 作为引用。

编辑:我最终将我尝试在 Python 和 C++ 中完成的所有功能暂时转移到 Python。我将在不久的将来更新有关尝试此问题评论中建议的策略的信息。

最佳答案

I am calling a python function embedded in C++ using the PyObject_CallFunction() call and I don't know what to do once I have the PyObject* to the returned data.

namedtuple 是一个元组子类,它另外将元组元素公开为命名属性。这意味着您可以选择是否以 obj[position]obj.attribute 的形式访问其数据。后者通常更具可读性,但前者与元组拆包结合得很好。在 Python/C 中,将它作为元组访问可能更容易,因为那时您可以使用方便的函数 PyArg_ParseTuple,如评论中所示。

要提取对象的任意属性(不一定是 namedtuple),可以调用 PyObject_GetAttrString。给定一个描述点的对象,提取诸如 x 之类的属性可能如下所示:

PyObject *point = ...;  // assume we get a new reference to point
if (!point)
return NULL;
PyObject *x = PyObject_GetAttrString(point, "x");
if (!x) {
// obj.x raised, possibly because point is of a different type
Py_DECREF(point);
return NULL;
}
double x_val = PyFloat_AsDouble(x);
Py_DECREF(x); // x not used below this line
if (x_val == -1 && PyErr_Occurred()) {
// obj.x is not float or float-like
Py_DECREF(point);
return NULL;
}
Py_DECREF(point); // point not used below this line

错误检查和引用计数非常繁琐,但可以使用保护类或更好的是使用其他人编写的类(例如 Boost.Python)来消除这些问题。

关于c++ - Python NamedTuple 到 C++ 结构,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/40321668/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com