python - 将 Python 结构解析为 PyObject

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

我从 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 代码中,我想通过解析 pValue 来更新我的 C 结构 bus,获取自:

  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

最佳答案

假设您正在使用 ctypes.Structure,您可以使用 Buffer interface 的实现.

尝试这样的事情:

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

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

关于python - 将 Python 结构解析为 PyObject,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/29464537/

相关文章:

python - 通过 OAuth2 服务帐户使用 Chrome Store Publishing API

c - 在终端中出现错误“\365\277\357\376”

c - 如何用C画一个椭圆?

c++ - 'PyCObject_Import ("cairo", "CAPI")' C++ call yields segfault, ' import cairo' 在 python 上有效

python - PyQt:十六进制的 QLineEdit 输入掩码

python - SQLite 将 2 个表内连接到一个主表中

python - 从 Lotus Notes View 获取数据的有效方法

c++ - 告诉dlopen先在哪个库中搜索符号

python - 子目录结构破坏了 C++ 扩展构建

c++ - 嵌入Python 3.3 : How do I access _PyParser_Grammar?