Navigation Menu

Skip to content

Instantly share code, notes, and snippets.

@guyarad
Forked from lucasea777/build.sh
Created November 26, 2019 07:28
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save guyarad/2f89f0038532dd125637cc638465e265 to your computer and use it in GitHub Desktop.
Save guyarad/2f89f0038532dd125637cc638465e265 to your computer and use it in GitHub Desktop.
Python C Extension Hello World
gcc -fpic --shared $(python3-config --includes) greetmodule.c -o greet.abi3.so
# can also use $(pkg-config --cflags python-3.5)
# or
# python3 setup.py install --record files.txt --user
#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}
};
static struct PyModuleDef greet =
{
PyModuleDef_HEAD_INIT,
"greet", /* name of module */
"", /* module documentation, may be NULL */
-1, /* size of per-interpreter state of the module, or -1 if the module keeps state in global variables. */
GreetMethods
};
PyMODINIT_FUNC PyInit_greet(void)
{
return PyModule_Create(&greet);
}
import greet
def main():
greet.greet('World')
if __name__ == "__main__":
main()
from setuptools import setup, Extension
setup(
name='greet',
version='1.0',
description='Python Package with Hello World C Extension',
ext_modules=[
Extension(
'greet',
sources=['greetmodule.c'],
py_limited_api=True)
],
)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment