For the extended Python C

This paper describes how to extend python with C language. The example is the shear plate, add a string to the Windows settings for python (Clipboard) function. I used to write the following code when the environment is: windows xp, gcc.exe 4.7.2, Python 3.2.3.

The first step is to write the C language DLL

Create a clip.c file, as follows:

// Setting the UNICODE database, it can correctly reproduce wide character set
#define UNICODE

#include <windows.h>
#include <python.h>

// Set the text to the clipboard(Clipboard)
static PyObject *setclip(PyObject *self, PyObject *args)
{
  LPTSTR  lptstrCopy;
  HGLOBAL hglbCopy;
  Py_UNICODE *content;
  int len = 0;

  // The python UNICODE string and length into 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;
}

// Define export to Python method
static PyMethodDef ClipMethods[] = {
  {"setclip", setclip, METH_VARARGS,
   "Set string to clip."},
  {NULL, NULL, 0, NULL}
};

// The definition of Python model
static struct PyModuleDef clipmodule = {
  PyModuleDef_HEAD_INIT,
  "clip",
  NULL,
  -1,
  ClipMethods
};

// The initialization of Python model
PyMODINIT_FUNC PyInit_clip(void)
{
  return PyModule_Create(&clipmodule);
}

The second step is to write Python setup.py

Create a setup.py file, as follows:

from distutils.core import setup, 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 with Python compiler

Run the following command:

python setup.py build --compiler=mingw32 install

Will prompt the following error 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 inside the -mno-cygwin, will be deleted, and then you can run.

After normal operation, will generate a clip.pyd file, and copy the file to the %PYTHON installation directory in the%/Lib/site-packages directory

The fourth step to test the extension

Write a test.py, as follows:

# -*- encoding: gbk -*-

import clip

clip.setclip("Hello am")

Function

python test.py

To any one place paste, you can verify the correctness of.

Posted by Arno at November 25, 2013 - 3:59 PM