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 modeimport spam
spam.system('ls -la')
then it should print the current directory listing as output
Created
August 15, 2019 08:14
-
-
Save haxpor/4ee82482e0d9d36818d2d98ef4fe736e to your computer and use it in GitHub Desktop.
Example of writing extension with c++ for python with cpython.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#!/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]) |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#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