(Mar-24-2025, 05:37 PM)voidtrance Wrote: How can I embed the Python code into C code? Are you referring to PyRun_SimpleScriptFlags()? I am fine with embedding Python code into the C code.
I compiled an example, starting from the extension module
shown here, and I added Python code to define the subclass at module initialization. Here is the complete C code
// file mycextension.c
#define PY_SSIZE_T_CLEAN
#include <Python.h>
int multiplier(int a, int b)
{
return a * b;
}
static PyObject *c_multiplier(PyObject *self, PyObject *args)
{
int a;
int b;
int ret;
if (!PyArg_ParseTuple(args, "ii", &a, &b))
{
return NULL;
}
ret = multiplier(a, b);
return Py_BuildValue("i", ret);
}
static PyMethodDef module_methods[] = {
{"multiplier", c_multiplier, METH_VARARGS, "Multiply two numbers."},
{NULL, NULL, 0, NULL}};
static struct PyModuleDef c_extension =
{
PyModuleDef_HEAD_INIT,
"c_extension", // the name of the module in Python
"", // The docstring in Python
-1, /* size of per-interpreter state of the module, or -1 if the module keeps state in global variables. */
module_methods};
PyMODINIT_FUNC PyInit_c_extension(void)
{
PyObject *ns;
PyObject *mod;
char* code =
"import enum\n"
"@enum.unique\n"
"class ThreadType(enum.IntEnum):\n"
" THREAD1 = enum.auto()\n"
" THREAD2 = enum.auto()\n"
" THREAD3 = enum.auto()\n";
mod = PyModule_Create(&c_extension);
ns = PyObject_GetAttrString(mod, "__dict__");
PyRun_String(code, Py_file_input, ns, ns);
Py_DECREF(ns);
return mod;
}
Here is the setup.py file
from distutils.core import setup, Extension
module = Extension("c_extension", sources=["mycextension.c"])
setup(
name="c_extension",
version="0.1",
description="An example of C extension made callable to the Python API.",
ext_modules=[module],
)
All this is installed by invoking
python -m pip install .
in the extension's directory.
Here is the result in the Python console
>>> import c_extension
>>> c_extension.ThreadType.THREAD1
<ThreadType.THREAD1: 1>