Python and C extension implementation methods

Source: Internet
Author: User

One, Python and C extensions

CPython is written in C, and Python extensions can be written in C and easily ported to C + +.

The python extension that you write needs to be compiled into a shared library of. So.

The Python program.

Official Document: Https://docs.python.org/2/extending/extending.html#writing-extensions-in-c

Ii. examples

Spamspam.  System("ls-l")     

We need to create a SPAM.C file module, which is the C implementation. Must begin with

#include <Python.h>

The following implementations are implemented:

StaticPyobject *Spam_system (Pyobject*self, Pyobject *args) {    Const Char*comment; intSTS; if(! Pyarg_parsetuple (args,"s", &command)) returnNULL; STS=System (command); returnPy_buildvalue ("I", STS);}

The C function has two parameters in the Python extension of the above function: self, args, these two are required.

Third, module method and function initialization

1, define the module and help document. The module is called system, which specifies the execution function Spam_system, which helps the document "execute a shell command"

Static Pymethoddef spammethods[] = {     {"system""Execute a shell command . " },    0, NULL}};

After compiling, import the module, execute the following help command, the document will appear

In [5]: Help (spam) to help on module    spam:name    spamfile/usr/lib/python2.  6/site-packages/spam.sofunctions    System (...)        Execute a shell command.

2, initial spam, initialization module function must be init[module], consistent

void Initspam () {    py_initmodule ("spam", Spammethods);}

Third, compile

1, compile the module, you need to write setup.py file

# !/usr/bin/env python # -*-coding:utf-8-*-  from Import  "spam"Setup (name=mod, Ext_modules=[extension (MOD, sources=['  spam.c']))

Module name name and Extension module.

2, to compile

[[email protected] pycext]#python setup.py buildrunning buildrunning build_extbuilding'spam'EXTENSIONGCC-pthread-fno-strict-aliasing-o2-g-pipe-wall-wp,-d_fortify_source=2-fexceptions-fstack-protector--param= Ssp-buffer-size=4-m32-march=i686-mtune=atom-fasynchronous-unwind-tables-d_gnu_source-fpic-fwrapv-dndebug-o2-g- Pipe-wall-wp,-d_fortify_source=2-fexceptions-fstack-protector--param=ssp-buffer-size=4-m32-march=i686-mtune= Atom-fasynchronous-unwind-tables-d_gnu_source-fpic-fwrapv-fpic-i/usr/include/python2.6-c Spam.c-o build/ temp.linux-i686-2.6/spam.oin file included from/usr/include/python2.6/pyconfig.h:4,                  from/usr/include/python2.6/python.h:8,                  fromSpam.c:3:/usr/include/python2.6/pyconfig-32.h:1034:1: Warning:"_posix_c_source"Redefinedin file included from/usr/include/stdio.h:28,                  fromSpam.c:1:/usr/include/features.h:162:1: Warning:this isThe location of the previous Definitionin file included from/usr/include/python2.6/pyconfig.h:4,                  from/usr/include/python2.6/python.h:8,                  fromSpam.c:3:/usr/include/python2.6/pyconfig-32.h:1043:1: Warning:"_xopen_source"Redefinedin file included from/usr/include/stdio.h:28,                  fromSpam.c:1:/usr/include/features.h:164:1: Warning:this isThe location of the previous DEFINITIONGCC-pthread-shared Build/temp.linux-i686-2.6/spam.o-l/usr/lib-lpython2.6-o build/lib.linux-i686-2.6/spam.so

Generate a Build folder with Spam.so Library

[[email protected] pycext] # lsbuild  setup.py  spam.c

3. Installation

[[email protected] pycext] # python setup.py Install running installrunning buildrunning build_extrunning install_libcopying build/lib.linux-i686-2.6/spam.so- >/usr/lib/python2.6/site-/usr/lib/python2.6/site-packages/spam-0.0.0-py2.6.egg-/usr/lib/ Python2.6/site-packages/spam-0.0.0-py2.6.egg-info

Execute the command as above, and install it.

Iv. Use of modules

Import Spamin [2]: Spam.system ("ls-la")drwxr-xr-x.  3 root root 4096 Apr  8 22:07 drwxr-xr-x. Root root 4096 Apr  8 21:01. DRWXR-xr-x.  4 root root 4096 Apr  8 21:51 build-rw-r--r--.  1 root root  171 APR  8 21:48 setup.py-rw-r--r--.  1 root root  549 Apr  8 22:07 spam.cout[2]: 0In [

As above, for Python extension related content ...

Spam.c

#include <stdio.h>#include<stdlib.h>#include"Python.h"StaticPyobject *Spam_system (Pyobject*self, Pyobject *args) {    Const Char*command; intSTS; if(! Pyarg_parsetuple (args,"s", &command)) returnNULL; STS=System (command); returnPy_buildvalue ("I", STS);}StaticPymethoddef spammethods[] = {    {"system", Spam_system, Meth_varargs,"Execute a shell command."}, {null, NULL,0, NULL}};voidInitspam () {Py_initmodule ("spam", spammethods);}intMainintargcChar*argv[]) {    return 0;}

setup.py

# !/usr/bin/env python # -*-coding:utf-8-*-  from Import  "spam"Setup (name=mod, Ext_modules=[extension (MOD, sources=[ ' SPAM.C ']))

Python and C extension implementation methods

Related Article

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.