I am building a Python C Extension that can load images. To load a certain image, the user has to write the file path for that image.
The problem is that the user has to type the whole file path, even if the image is in the same directory as their module.
Python itself has some useful tools like os.path
and pathlib
that can help you to find the path of the current module.
I have searched the Python C API and I cannot seem to find any tools that relate to finding the current working directory in C.
What can I do - in C - to get the path to the directory of the user's module? Are there any Python.h functions? Am I taking the wrong approach?
The python c api can interact with lots of things you can do in Python.
How would you do this in Python? You would import os
and call os.getcwd()
, right?
Turns out you can do the same in the c api.
PyObject *os_module = PyImport_ImportModule("os");
if (os_module == NULL) { //error handling
return NULL;
}
PyObject* cwd = PyObject_CallMethod(os_module, "getcwd", NULL);
if (cwd == NULL) { //error handling
return NULL;
}
char* result = PyUnicode_AsUTF8(cwd);
And then when you're done with the module, or any pyobject in general, remember to call Py_DECREF()
on it.