备注:这里是我为培训写的PPT,网上资料较少,特此分享出来。
What is python extension?
The extension of python is that provided by other computer language such as C/C++.
Creating extensions for python involves three main steps:
1. Creating application code
2. Wrapping code with boilerplates
3. Compilation and testing
1. Creating application code
To call c function in python, we need program codes inherit corresponding wrap’s interface,and then Complier them as a python’s module.
2. Wrapping code with boilerplates
1). Include Python header file
#include “python.h”/< python.h >
2). Add PyObject* Module_func() Python wrappers for each module function
PyObject* method(PyObject* self, PyObject* args);
3). Add PyMethodDef ModuleMethods[] array/table for each module function
4). Add void initModule() module initialize function
3.Complier And Test
Python was default built with visual studio 2003. if you compile in dos, available compiler as follows:
1). create the setup.py file
from distutils.core import setup, Extension
MOD = ‘ModuleName‘
setup(name=MOD, ext_modules=[ Extension(MOD, sources=[‘C++fileName'])])
2). run “setup.py build” in commandline
3).copy the pyd file from “../Python25/build/lib.win32-2.5” folder to” ../Python25/DLLs” folder then we can import the extension in python.
4).Import And Test
A simple example for python extensions.
setp1: open Lcc-win32,choose file/new/file, create file type as follows:
Click ok button.
Create hello.c script, save this file.
#include
#include
static PyObject *message(PyObject *self, PyObject *args)
{
char *fromPython, result[64];
if (!PyArg_Parse(args, "(s)", &fromPython))
return NULL;
else
{
strcpy(result, "Hello, ");
strcat(result, fromPython);
return Py_BuildValue("s", result);
}
}
static PyMethodDef
helloMethods[] =
{
{"message", message, 1},
{NULL, NULL},
};
void inithello()
{
Py_InitModule("hello", helloMethods);
}
2.Copy hello.c file to python root directory. For example: “C:/Python25”
3. Create a setup.py file in “C:/Python25”.
from distutils.core import setup, Extension
MOD = 'hello'
setup(name=MOD, ext_modules=[
Extension(MOD, sources=['hello.c'])])
4. Open your windows shell window,entry into your python root, then input this command as follows:
5).copy the pyd file from “../Python25/build/lib.win32-2.5” folder to” ../Python25/DLLs” folder then we can import the extension in python.
6).Import And Test
Now, Import successfully!