Get Current Working Directory With Python C Extension

Solution 1:

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.