Question

I have PythonCode.py:

import os, ctypes
print "ctypes are imported"

And CCode.c:

...
PySys_SetPath(path_to_PythonCode);
PyObject *pModule = PyImport_ImportModule("PythonCode");
if (!pModule) {
  PyErr_Print();
  return;
}
...

PyErr_Print() prints:

Traceback (most recent call last):   File ".../PythonCode.py", line 1,
  in <module> import os, ctypes
ImportError: No module named ctypes

Executing Python code in terminal shows that ctypes do exist:

$ python --version
Python 2.7.1
$ python PythonCode.py
ctypes are imported

Why Python/C API cannot import ctypes?

Was it helpful?

Solution

You replaced the default sys.path list with a single path. Instead you can insert the new path:

PyObject *sys_path, *path;

sys_path = PySys_GetObject("path");
if (sys_path == NULL || !PyList_Check(sys_path)) {   
    /* ZOMG! That's so wrong... */
    return;
}
path = PyString_FromString(path_to_PythonCode);
PyList_Insert(sys_path, 0, path);
Py_DECREF(path);
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top