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 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 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 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() |
thanks! it worked fine to me
Tried and Mac and Ubuntu. Both complain about missing Python.h
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
python3 version --> https://gist.github.com/lucasea777/8801440f6b622edd3553c8a7304bf94e :)