Skip to content

Instantly share code, notes, and snippets.

@autf
Last active March 21, 2023 05:30
Show Gist options
  • Save autf/509ad826904cafcb10560aa8e7d79b11 to your computer and use it in GitHub Desktop.
Save autf/509ad826904cafcb10560aa8e7d79b11 to your computer and use it in GitHub Desktop.
An offical example of embedding Python in C + an unofficial Makefile
run: pt
./pt
pt: printime.c
cc `python3-config --cflags` -o $@ $^ `python3-config --ldflags --embed`
clear:
rm -f pt
// src: https://docs.python.org/dev/extending/embedding.html#very-high-level-embedding
#define PY_SSIZE_T_CLEAN
#include <Python.h>
int
main(int argc, char *argv[])
{
wchar_t *program = Py_DecodeLocale(argv[0], NULL);
if (program == NULL) {
fprintf(stderr, "Fatal error: cannot decode argv[0]\n");
exit(1);
}
Py_SetProgramName(program); /* optional but recommended */
Py_Initialize();
PyRun_SimpleString("from time import time,ctime\n"
"print('Today is', ctime(time()))\n");
if (Py_FinalizeEx() < 0) {
exit(120);
}
PyMem_RawFree(program);
return 0;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment