Skip to content

Instantly share code, notes, and snippets.

@Artanis
Created September 17, 2011 08:43
Show Gist options
  • Save Artanis/1223762 to your computer and use it in GitHub Desktop.
Save Artanis/1223762 to your computer and use it in GitHub Desktop.
Python C Extension Hello World
gcc -fpic --shared $(python-config --includes) greetmodule.c -o greetmodule.so
#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);
}
import greet
def main():
greet.greet('World')
if __name__ == "__main__":
main()
@lucasea777
Copy link

@carlosmsx
Copy link

thanks! it worked fine to me

@MagnusBrzenk
Copy link

Tried and Mac and Ubuntu. Both complain about missing Python.h

@MalteGruber
Copy link

MalteGruber commented Jul 13, 2020

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 used python3.8-config --includes.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment