我遇到了一个使用纯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}$
要从方法调用中提取参数,需要查看Parsing arguments and building values中记录的函数,例如^{} 。(如果您只使用位置参数,那么这是因为!还有其他用于位置和关键字参数等。)
从
PyArg_ParseTuple
返回的对象的引用计数没有增加。对于简单的C函数,您可能不需要担心这个问题。如果要与其他Python/C函数交互,或者释放全局解释器锁(即允许线程),则需要非常仔细地考虑对象所有权。在要调用对象上的方法,需要使用^{} 或^{} ,这取决于如何构造参数列表和方法名。请参阅我在代码中关于对象所有权的注释!在
快速离题只是为了确保你不会为以后的失败做好准备:如果你真的只是得到字符串来打印它,那么最好只是获取对象引用并将其传递给^{} 。当然,也许这只是为了说明,或者你比我更清楚你想如何处理这些数据;)
^{pr2}$现在,Concrete Objects Layer文档的String/Bytes Objects部分中有许多函数;请使用最适合您的函数。在
但是不要忘记这一点:
注意^{} 的用法,并且注意它不是
return Py_RETURN_NONE
!在这段代码的结构在很大程度上是由个人风格决定的(例如早期返回,
static char
在函数内格式化字符串,初始化为NULL
)。希望重要的信息是清楚的,除了文体惯例。在相关问题 更多 >
编程相关推荐