Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
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

lucasea777 commented May 19, 2018

@carlosmsx
Copy link

carlosmsx commented Jul 5, 2018

thanks! it worked fine to me

@MagnusBrzenk
Copy link

MagnusBrzenk commented Dec 6, 2019

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