Created
December 21, 2017 14:13
-
-
Save sbmueller/d645f32e8413d9799c7d087f77dcfa7b to your computer and use it in GitHub Desktop.
Basic C++ Python Extension
This file contains 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
/* | |
This file will create a python module named `hello` (l. 42) | |
It's important that the project is set to output a file named | |
`hello.pyd` which must be identical to the module name. | |
Python will then search for the method `PyInit_hello(void)` | |
and call it. There, `PyModule_Create` must be called with | |
a `struct PyModuleDef` as argument. | |
Within there, the module's methods are defined. This is done | |
via a `PyMethodDef` mapping Python methods to the according | |
C++ methods. | |
Lastly, methods can be defined, returning and taking `PyObject*`s. | |
If nothing is returned, `Py_RETURN_NONE` must be called. | |
*/ | |
#include <Python.h> | |
static PyObject* | |
say_hello(PyObject* self, PyObject* args) | |
{ | |
const char* name; | |
if (!PyArg_ParseTuple(args, "s", &name)) | |
return NULL; | |
printf("Hello %s!\n", name); | |
Py_RETURN_NONE; | |
} | |
static PyMethodDef HelloMethods[] = { | |
{"hello", say_hello, METH_VARARGS, "Say Hello."}, | |
{NULL, NULL, 0, NULL} /* Sentinel */ | |
}; | |
static struct PyModuleDef HelloModule = | |
{ | |
PyModuleDef_HEAD_INIT, | |
"hello", /* name of module */ | |
NULL, /* module documentation, may be NULL */ | |
-1, /* size of per-interpreter state of the module, | |
or -1 if the module keeps state in global variables. */ | |
HelloMethods | |
}; | |
PyMODINIT_FUNC | |
PyInit_hello(void) | |
{ | |
return PyModule_Create(&HelloModule); | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment