jleeothon
jleeothon

Reputation: 3146

Import standard Python library from C

I am writing a Python 3 C extension where I want to use a MappingProxyType (from types import MappingProxyType). From what I saw in the Cpython source code, MappingProxyType is written in Python and not in C.

How can I use this type from C? I imagine there must be something like an C-level "import" and then I could find the PyObject (or rather, PyTypeObject) from the name as a C string.

Upvotes: 0

Views: 126

Answers (1)

tynn
tynn

Reputation: 39843

There's a C API for for importing modules. Then you just need to get the MappingProxyType type attribute from the module:

static PyTypeObject *import_MappingProxyType(void) {
    PyObject *m = PyImport_ImportModule("types");
    if (!m) return NULL;
    PyObject *t = PyObject_GetAttrString(m, "MappingProxyType");
    Py_DECREF(m);
    if (!t) return NULL;
    if (PyType_Check(t))
        return (PyTypeObject *) t;
    Py_DECREF(t);
    PyErr_SetString(PyExc_TypeError, "not the MappingProxyType type");
    return NULL;
}

Upvotes: 1

Related Questions