Step by step to write Python extensions in C language

Source: Internet
Author: User

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). I was writing ...

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:

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465 // 设置 UNICODE 库,这样的话才可以正确复制宽字符集#define UNICODE  #include <windows.h>#include <python.h> // 设置文本到剪切板(Clipboard)staticPyObject *setclip(PyObject *self, PyObject *args){  LPTSTRlptstrCopy;  HGLOBALhglbCopy;  Py_UNICODE *content;  intlen = 0;   // 将 python 的 UNICODE 字符串及长度传入  if(!PyArg_ParseTuple(args, "u#", &content, &len))    returnNULL;   Py_INCREF(Py_None);   if(!OpenClipboard(NULL))    returnPy_None;   EmptyClipboard();   hglbCopy = GlobalAlloc(GMEM_MOVEABLE, (len+1) * sizeof(Py_UNICODE));  if(hglbCopy == NULL) {    CloseClipboard();    returnPy_None;  }   lptstrCopy = GlobalLock(hglbCopy);  memcpy(lptstrCopy, content, len * sizeof(Py_UNICODE));  lptstrCopy[len] = (Py_UNICODE) 0;   GlobalUnlock(hglbCopy);   SetClipboardData(CF_UNICODETEXT, hglbCopy);    CloseClipboard();   returnPy_None;} // 定义导出给 python 的方法staticPyMethodDef ClipMethods[] = {  {"setclip", setclip, METH_VARARGS,   "Set string to clip."},  {NULL, NULL, 0, NULL}}; // 定义 python 的 modelstaticstructPyModuleDef clipmodule = {  PyModuleDef_HEAD_INIT,  "clip",  NULL,  -1,  ClipMethods}; // 初始化 python modelPyMODINIT_FUNC PyInit_clip(void){  returnPyModule_Create(&clipmodule);}

The second step is to write the Python setup.py

Create a setup.py file that reads as follows:

123456789 fromdistutils.core importsetup, Extension module1 =Extension(‘clip‘,                    sources =[‘clip.c‘]) setup (name =‘clip‘,       version =‘1.0‘,       description =‘This is 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:

123 # -*- encoding: gbk -*-importclipclip.setclip("Hello python")

Run

Python test.py

Paste it anywhere else to verify that it is correct.

Step by step to write Python extensions in C language

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.