[Python编程(第4版)].(Programming.Python.4th.Edition).Mark.Lutz.文字版

(yzsuai) #1

else {
strcpy(result, "Hello, "); / build up C string /
strcat(result, fromPython); / add passed Python string /
return Py_BuildValue("s", result); / convert C -> Python /
}
}


/ registration table /
static PyMethodDef hello_methods[] = {
{"message", message, METH_VARARGS, "func doc"}, / name, &func, fmt, doc /
{NULL, NULL, 0, NULL} / end of table marker /
};


/ module definition structure /
static struct PyModuleDef hellomodule = {
PyModuleDef_HEAD_INIT,
"hello", / name of module /
"mod doc", / module documentation, may be NULL /
−1, / size of per-interpreter module state, −1=in global vars /
hello_methods / link to methods table /
};


/ module initializer /
PyMODINIT_FUNC
PyInit_hello() / called on first import /
{ / name matters if loaded dynamically /
return PyModule_Create(&hellomodule);
}


This C module has a 4-part standard structure described by its comments, which all C
modules follow, and which has changed noticeably in Python 3.X. Ultimately, Python
code will call this C file’s message function, passing in a string object and getting back
a new string object. First, though, it has to be somehow linked into the Python inter-
preter. To use this C file in a Python script, compile it into a dynamically loadable object
file (e.g., hello.so on Linux, hello.dll under Cygwin on Windows) with a makefile like
the one listed in Example 20-2, and drop the resulting object file into a directory listed
on your module import search path exactly as though it were a .py or .pyc file.


Example 20-2. PP4E\Integrate\Extend\Hello\makefile.hello


#############################################################


Compile hello.c into a shareable object file on Cygwin,


to be loaded dynamically when first imported by Python.


#############################################################


PYLIB = /usr/local/bin
PYINC = /usr/local/include/python3.1


hello.dll: hello.c
gcc hello.c -g -I$(PYINC) -shared -L$(PYLIB) -lpython3.1 -o hello.dll


clean:
rm -f hello.dll core


1488 | Chapter 20: Python/C Integration

Free download pdf