简体   繁体   中英

No module named ctypes using Python/C API

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?

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);

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM