Skip to content

Instantly share code, notes, and snippets.

@haxpor
Created August 15, 2019 08:14
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save haxpor/4ee82482e0d9d36818d2d98ef4fe736e to your computer and use it in GitHub Desktop.
Save haxpor/4ee82482e0d9d36818d2d98ef4fe736e to your computer and use it in GitHub Desktop.
Example of writing extension with c++ for python with cpython.

How to build

  • python3 setup.py build
  • From current directory, cd build/lib.linux-x86_64-3.6 (tested on Ubuntu 18.04 with python 3.6.7).
  • python3 to enter interactive mode
  • import spam
  • spam.system('ls -la') then it should print the current directory listing as output
#!/usr/bin/env python3
# encoding: utf-8
from distutils.core import setup, Extension
spam_module = Extension('spam', sources=['spammodule.cpp'])
setup(name='spam',
version='0.1.0',
description='Spammodule written in C++',
ext_modules=[spam_module])
#define PY_SSIZE_T_CLEAN
#include <Python.h>
static PyObject *spam_system(PyObject *self, PyObject *args)
{
const char *command;
int sts;
if (!PyArg_ParseTuple(args, "s", &command))
return NULL;
sts = system(command);
return PyLong_FromLong(sts);
}
// module methods
static PyMethodDef SpamModuleMethods[] = {
{ "system", spam_system, METH_VARARGS, "Execute system's command line from input string." }
};
// module definition
static PyModuleDef SpamModuleDef = {
PyModuleDef_HEAD_INIT,
"SpamModule",
"SpamModule for practicing",
-1,
SpamModuleMethods
};
PyMODINIT_FUNC PyInit_spam(void)
{
Py_Initialize();
return PyModule_Create(&SpamModuleDef);
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment