Created
September 17, 2011 08:43
-
-
Save Artanis/1223762 to your computer and use it in GitHub Desktop.
Python C Extension Hello World
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
gcc -fpic --shared $(python-config --includes) greetmodule.c -o greetmodule.so |
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
#include <Python.h> | |
static PyObject * | |
greet_name(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 GreetMethods[] = { | |
{"greet", greet_name, METH_VARARGS, "Greet an entity."}, | |
{NULL, NULL, 0, NULL} | |
}; | |
PyMODINIT_FUNC | |
initgreet(void) | |
{ | |
(void) Py_InitModule("greet", GreetMethods); | |
} |
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
import greet | |
def main(): | |
greet.greet('World') | |
if __name__ == "__main__": | |
main() |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Perfect! Just be sure to update the
python-config --includes
part of the gcc call to fit your python version, so for instance for python 3.8 I usedpython3.8-config --includes
.