I copied the first half of the tutorial extension of Python with C and C ++. I was thinking of studying Cython, but I happened to see a blog post about the above method, so I felt like trying it. I have the impression that it will not be that difficult. I don't know the API or anything yet. .. Really squeeze spammodule.c as a tutorial. Paste the comments as they are in the tutorial text.
spammodule.c
#include <Python.h>
static PyObject *
spam_system(PyObject *self, PyObject *args)
{
const char *command;
int sts;
if (!PyArg_ParseTuple(args, "s", &command))
/*A Python string or Unicode object that points to a character string
Convert to C pointer. "s"Meaning of
*/
return NULL;
sts = system(command);
return Py_BuildValue("i", sts);
/*A new Python object that takes a formatted string and any number of C values as arguments
return it. "i"Means an integer object*/
}
static PyMethodDef SpamMethods[] = {
{"system", spam_system, METH_VARARGS,
"Description Execute a shell command."},
{NULL, NULL, 0, NULL}
};
PyMODINIT_FUNC
initspam(void)
{
(void) Py_InitModule("spam", SpamMethods);
}
After writing safely, create setup.py as follows.
I referred to this article .
setup.py
from distutils.core import setup, Extension
module1 = Extension('spam',
sources = ['spammodule.c'])
setup (name = 'Spam',
version = '1.0',
description = 'This is a spam package',
ext_modules = [module1])
The rest is on the command line
$python setup.py build
(This time it's an experiment, so I won't install it) To execute. Then, a directory called build will be created directly under the current. I think that the contents differ depending on the environment, but if you specify the path of spam.so and import it It seems that it can be used. I copied and pasted spam.so into a suitable directory (Is it okay?) It was a suitable memo.
Recommended Posts