I have Python extension module written in C. I want to use in this C code one of the standard Python modules, for example os
or shutil
. How is best to do this?
You need include Python. h header file in your C source file, which gives you access to the internal Python API used to hook your module into the interpreter. Make sure to include Python. h before any other headers you might need.
You'll need a file called setup.py to install your application. For this tutorial, you'll be focusing on the part specific to the Python C extension module.
Building C and C++ Extensions with distutils. Extension modules can be built using distutils, which is included in Python. Since distutils also supports creation of binary packages, users don't necessarily need a compiler and distutils to install the extension.
PyObject* os = PyImport_ImportModuleNoBlock("os");
if (os == NULL)
return NULL;
someattr = PyObject_GetAttrString(os, "someattr");
Py_DECREF(os);
If you import the module only once e.g., in init_yourmodule()
function then use PyImport_ImportModule("os")
.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With