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對象,而後者通常用來表示錯誤,就像我們見到的那樣。

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章