【问题标题】:Parsing Python Structure as PyObject将 Python 结构解析为 PyObject
【发布时间】:2023-03-11 08:55:01
【问题描述】:

我正在从 python 函数返回以下结构的对象

class Bus(Structure):
    _fields_ = [ ("a", c_int), 
                 ("b", c_char), 
                 ("c", c_float), 
                 ("d", c_double), 
                 ("e", c_char_p) 
               ]

def GetBus(  *args, **kwargs ):
    Signal = cast(c_char_p(kwargs['Bus']), POINTER(Bus )).contents
    ## Logic that updates Signal
    return Signal

在我的 C 代码中,我想更新我的 C 结构 bus,通过解析从以下获得的 pValue

  Bus bus ;
  python_Bus = Py_BuildValue("s#",  (char* )&bus,  sizeof(Bus)) ;
  PyDict_SetItemString( pDict,"Bus", python_Bus ) ;

  PyObject* pValue = PyObject_Call(pFunc, pArgs,pDict) ;

如何解析 pValue

Py???_???(pvalue, ???) ; 吗?或如何将其转换为 char* 并在我的 C 代码中执行 memcpy(如果这是一种方式)?


我也尝试创建一个新的 Python 类型,但看起来这一切都归结为我的“getter”函数中的Py_BuildValue,而且我不希望每个元素都有多个“setters”。

使用 Python2.7

【问题讨论】:

    标签: python c python-c-api python-embedding


    【解决方案1】:

    假设你使用ctypes.Structure,你可以使用Buffer interface的实现。

    尝试类似:

    Py_buffer view = { 0 };
    PyObject_GetBuffer(pvalue, &view, PyBUF_SIMPLE);
    // use view.buf, which is of void*
    PyBuffer_Release(&view);
    

    您可能需要添加一些错误处理以确保获得正确的数据。

    【讨论】:

    • 谢谢!按预期工作。如果我将我的 C bus 正确 传递给 Python,您能否发表评论?它有效,但如果我做任何愚蠢的事情或有任何其他好方法,我想得到评论
    • 我会创建一个new type 并在两边都使用它。为什么要使用 ctypes?
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2023-03-16
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多