在Python中向C模块传递对象

2024-10-01 02:26:10 发布

您现在位置:Python中文网/ 问答频道 /正文

我遇到了一个使用纯python和C python模块的情况。 总而言之,在C模块中我如何接受和操作python对象? 我的python部分将如下所示。在


    #!/usr/bin/env python

    import os, sys
    from c_hello import *

    class Hello:
        busyHello = _sayhello_obj

    class Man:
        def __init__(self, name):
            self.name = name
        def getName(self):
            return self.name

    h = Hello()
    h.busyHello( Man("John") )

在C语言中,有两件事需要解决。 首先,如何接收对象? 第二,如何从对象调用方法?在

^{pr2}$

Tags: 模块对象nameimportselfenvhellobin
1条回答
网友
1楼 · 发布于 2024-10-01 02:26:10

要从方法调用中提取参数,需要查看Parsing arguments and building values中记录的函数,例如^{}。(如果您只使用位置参数,那么这是因为!还有其他用于位置和关键字参数等。)

PyArg_ParseTuple返回的对象的引用计数没有增加。对于简单的C函数,您可能不需要担心这个问题。如果要与其他Python/C函数交互,或者释放全局解释器锁(即允许线程),则需要非常仔细地考虑对象所有权。在

static PyObject *
_sayhello_obj(PyObject *self, PyObject *args)
{
  PyObject *obj = NULL;
  // How can I fill obj?

  static char fmt_string = "O" // For "object"

  int parse_result = PyArg_ParseTuple(args, fmt_string, &obj);

  if(!parse_res)
  {
    // Don't worry about using PyErr_SetString, all the exception stuff should be
    // done in PyArg_ParseTuple()
    return NULL;
  }

  // Of course, at this point you need to do your own verification of whatever
  // constraints might be on your argument.

要调用对象上的方法,需要使用^{}^{},这取决于如何构造参数列表和方法名。请参阅我在代码中关于对象所有权的注释!在

快速离题只是为了确保你不会为以后的失败做好准备:如果你真的只是得到字符串来打印它,那么最好只是获取对象引用并将其传递给^{}。当然,也许这只是为了说明,或者你比我更清楚你想如何处理这些数据;)

^{pr2}$

现在,Concrete Objects Layer文档的String/Bytes Objects部分中有许多函数;请使用最适合您的函数。在

但是不要忘记这一点:

  // Now that we're done with the object we obtained, decrement the reference count
  Py_XDECREF(objname);

  // You didn't mention whether you wanted to return a value from here, so let's just
  // return the "None" singleton.
  // Note: this macro includes the "return" statement!
  Py_RETURN_NONE;
}

注意^{}的用法,并且注意它不是return Py_RETURN_NONE!在

这段代码的结构在很大程度上是由个人风格决定的(例如早期返回,static char在函数内格式化字符串,初始化为NULL)。希望重要的信息是清楚的,除了文体惯例。在

相关问题 更多 >