Python名称错误:名称'ctypes'未定义。

8
我正在尝试从自定义.dll文件中调用函数。但是当我尝试加载我的库SDK.dll时,我会收到以下错误。我正在遵循此处找到的指示: Python import dll 有人知道问题出在哪里吗?我只发现这个问题适用于MAC环境的参考资料。
>>> from ctypes import *
>>> lib = ctypes.WinDLL('C:/Develop/test/SDK.dll')

Traceback (most recent call last):
  File "<pyshell#19>", line 1, in <module>
    lib = ctypes.WinDLL('C:/Develop/test/SDK.dll')
NameError: name 'ctypes' is not defined
2个回答

11

通过执行 from ctypes import * 语句,你将从 ctypes 模块中导入所有内容到本地命名空间,因此应直接调用 WinDLL

>>> from ctypes import *
>>> lib = WinDLL('C:/Develop/test/SDK.dll')

另一种方法(通常更好,如NPE所述)是仅导入ctypes

>>> import ctypes
>>> lib = ctypes.WinDLL('C:/Develop/test/SDK.dll')

非常感谢,它起作用了。现在我又遇到了另一个错误,Traceback (most recent call last): File "<pyshell#21>", line 1, in <module> lib = ctypes.WinDLL('C:/Develop/test/SDKApplication/Debug/SDKCore.dll') File "C:\Python27\lib\ctypes\__init__.py", line 365, in __init__ self._handle = _dlopen(self._name, mode) WindowsError: [Error 193] %1 不是有效的 Win32 应用程序,但我认为这可能是因为我的 Python 是 32 位的,而 dll 是 64 位的原因。 - toni

5

变更

from ctypes import *

为了

import ctypes

前者会将ctypes中的所有名称导入到当前命名空间中。这通常被认为是一种不好的做法,最好避免使用。


非常感谢,它起作用了。现在我又遇到了另一个错误,Traceback (most recent call last): File "<pyshell#21>", line 1, in <module> lib = ctypes.WinDLL('C:/Develop/test/SDKApplication/Debug/SDKCore.dll') File "C:\Python27\lib\ctypes\__init__.py", line 365, in __init__ self._handle = _dlopen(self._name, mode) WindowsError: [Error 193] %1 不是有效的 Win32 应用程序,但我认为这可能是因为我的 Python 是 32 位的,而 dll 是 64 位的原因。 - toni

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接