Extending and Embedding the Python Interpreter(三)

Going back to our example function, you should now be able to understand this statement:

 

    

It returns NULL (the error indicator for functions returning object pointers) if an error is detected in the argument list, relying on the exception set by PyArg_ParseTuple(). Otherwise the string value of the argument has been copied to the local variable command. This is a pointer assignment and you are not supposed to modify the string to which it points (so in Standard C, the variable command should properly be declared as "const char *command").

回到我们前面的例子,如果PyArg_ParseTuple()函数在执行过程中发生异常,那么这段代码需要返回一个NULL值表示错误。否则的话,表示参数的字符串会被复制到本地变量command中。command是一个指向字符串的指针常量,在这里并不能去修改这个指针所指向的字符串。

The next statement is a call to the Unix function system(), passing it the string we just got from PyArg_ParseTuple():

 

   

Our spam.system() function must return the value of sts as a Python object. This is done using the function Py_BuildValue(), which is something like the inverse of PyArg_ParseTuple(): it takes a format string and an arbitrary number of C values, and returns a new Python object. More info on Py_BuildValue() is given later.

接下去我们要做的就是把刚才得到的代表参数的字符串传入函数system中。当我们在python中调用spam.system()时,我们必须把sts表示成一个python对象。这需要通过Py_BuildValue()函数来实现,这在某种程度上似乎与PyArg_ParseTuple()函数的作用相反:它使用一个format字符串和任意个C代码中的值,把它们转换为一个python对象。

return Py_BuildValue("i", sts);

In this case, it will return an integer object. (Yes, even integers are objects on the heap in Python!)

If you have a C function that returns no useful argument (a function returning void), the corresponding Python function must return None. You need this idiom to do so (which is implemented by the Py_RETURN_NONE macro):

如果用C代码编写的函数没有返回值,那么相应的python函数需要返回None。需要使用下面这种用法

 

    

Py_None is the C name for the special Python object None. It is a genuine Python object rather than a NULL pointer, which means ``error'' in most contexts, as we have seen.

Py_None是C语言中用来代表python 对象None的,它不同于NULL指针,它是真正的python对象,而后者通常用来表示错误,就像我们见到的那样。

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值