没有使用Python/C API的名为ctypes的模块

2024-06-11 23:15:25 发布

您现在位置:Python中文网/ 问答频道 /正文

我有Python代码

import os, ctypes
print "ctypes are imported"

以及CCode.c:

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

PyErr_Print()打印:

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

在终端中执行Python代码表明ctypes确实存在:

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

为什么Python/C API不能导入ctypes?


Tags: 代码pyimportosctypesaremoduleprint
1条回答
网友
1楼 · 发布于 2024-06-11 23:15:25

您用一个路径替换了默认的sys.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);

相关问题 更多 >