Search This Blog

Labels

Friday, December 17, 2010

《扩展和嵌入Python解释器(译稿)》1.3 Back to the Example

1.3 Back to the Example 示例回顾

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

回到我们例子中的函数,你现在应该能理解这条语句:

if (!PyArg_ParseTuple(args, "s", &command))

    return NULL;

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’).

当参数列表中检测到错误则函数返回一个NULL 指针(函数返回对象指针时发生错误的标识符),这依赖于由 PyArg_ParseTuple() 设置的异常。此外,参数的字符串的值拷贝给局部变量command。这是一个指针赋值,并且你不应当修改它所指向的字符串(所以在标准C 中,command 变量应当正确地声明为‘const char *command’)

The next statement is a call to the UNIX function system(), passing it the string we just got from PyArg_-ParseTuple():

下一条语句是对UNIX 函数 system() 的一个调用,将我们从PyArg_-ParseTuple()得到的字符串传入:

sts = system(command);

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 ofPyArg_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.

我们的spam.system()函数必须以Python对象的形式返回sts的值。这由Py_BuildValue()函数实现,它有点像PyArg_ParseTuple()的逆操作:接收一个格式转换码和任意一个 C 变量值,返回一个新的Python 对象。有关Py_BuildValue() 更多的信息会在后面给出。

return Py_BuildValue("i", sts);

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

在这,它将返回一个整型数。(是的,甚至整型数在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):

如果有一个返回无效参数的函数(一个返回void的函数),则对应的Python函数必须返回None。你也需要这个风格(由Py_RETURN_NONE macro 实现)

Py_INCREF(Py_None);

return Py_None;

Py_Noneis 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是Python特殊对象None 在C 中的名字。它是一个真正的Python对象,而不是一个NULL 指针,正如我们看到了的,在大多数上下文中 NULL 意味着错误。

No comments:

Post a Comment