This article describes how to extend Python with the C language. As an example, add a function for Python to set the string to the Windows clipboard (Clipboard). The environment I used to write the following code is: Windows XP, Gcc.exe 4.7.2, Python 3.2.3.
The first step is to compose the C language DLL
Create a clip.c file that reads as follows:
Set up a Unicode library so that the wide character set # # UNICODE #include can be copied correctly
#include
Set Text to clipboard (Clipboard) static Pyobject *setclip (Pyobject *self, Pyobject *args) {LPTSTR lptstrcopy; Hglobal hglbcopy; Py_unicode *content; int len = 0; Pass the Python UNICODE string and length to the IF (! Pyarg_parsetuple (args, "u#", &content, &len)) return NULL; Py_incref (Py_none); if (! OpenClipboard (NULL)) return py_none; EmptyClipboard (); Hglbcopy = GlobalAlloc (gmem_moveable, (len+1) * sizeof (Py_unicode)); if (hglbcopy = = NULL) {CloseClipboard (); return py_none; } lptstrcopy = GlobalLock (hglbcopy); memcpy (lptstrcopy, content, Len * sizeof (Py_unicode)); Lptstrcopy[len] = (py_unicode) 0; GlobalUnlock (hglbcopy); SetClipboardData (Cf_unicodetext, hglbcopy); CloseClipboard (); return py_none;} Defines the method that is exported to Python static pymethoddef clipmethods[] = {{"SetClip", SetClip, Meth_varargs, "Set string to clip."}, {NU LL, NULL, 0, NULL}}; Define Python's modelstatic struct pymoduledef clipmodule = {pymoduledef_head_init, "clip", NULL,-1, CliPmethods}; Initialize Python modelpymodinit_func pyinit_clip (void) {return pymodule_create (&clipmodule);}
The second step is to write the Python setup.py
Create a setup.py file that reads as follows:
From Distutils.core Import Setup, Extension module1 = Extension (' clip ', sources = [' clip.c ']) setup (name = ' Clip ', Version = ' 1.0 ', description = ' This was a clip package ', ext_modules = [Module1]
The third step is to compile with Python
Run the following command:
Python setup.py build--compiler=mingw32 Install
The following error is prompted in my environment:
gcc:error:unrecognized command line option '-mno-cygwin '
Error:command ' gcc ' failed with exit status 1
Open the%python installation directory%/lib/distutils/cygwinccompiler.py file, delete the-mno-cygwin inside, and then run it again.
After normal operation, a Clip.pyd file is generated and the file is copied to the%python installation directory%/lib/site-packages directory
The fourth step tests the extension
Write a test.py that reads as follows:
#-*-ENCODING:GBK-*-import clipclip.setclip ("Hello python")
Run
Python test.py
Paste it anywhere else to verify that it is correct.