奇怪的 Python ctypes 行为。始终加载 m(数学)库
Strange Python ctypes behavior. Always loads the m (math) library
有人可以向我解释为什么以下 Python 代码有效吗?
import ctypes
import ctypes.util
boblib = ctypes.cdll.LoadLibrary(ctypes.util.find_library("bob_is_your_uncle"))
boblib.cos.argtypes = [ctypes.c_double]
boblib.cos.restype = ctypes.c_double
print(boblib.cos(0)) # This prints out "1.0"
我 1000% 确定我的文件系统上没有 "bob_is_your_uncle" 库。然而,似乎 ctypes 加载了 m
库。为什么会这样?
另外,如果我这样做:print(boblib)
,我得到这个:
<CDLL 'None', handle 7f6a80f6d170 at 0x7f6a7f34d0b8>
CDLL 'None'
是什么意思?
提前致谢。
PS:在我的两个 Python 解释器上执行 --version
我得到:
Python 3.6.5rc1
和 Python 2.7.14+
。上面的代码在两个版本上给出了相同的结果。我的 OS 是 Debian(测试仓库)。
它没有加载数学库。它似乎正在加载 Python 可执行文件本身,其中链接了 cos
。
确实没有名为bob_is_your_uncle
的库,所以find_library
returnsNone
。 (这就是您看到的输出中 None
的来源。)
在 Unix 上,LoadLibrary
逻辑有一个 specific check that translates a None
name to a null pointer for the underlying dlopen
routine. dlopen
has special handling 用于空名称:
If filename is NULL, then the returned handle is for the main program.
事实上,在 Unix 上,ctypes.pythonapi
是 created 和
pythonapi = PyDLL(None)
首先解释为什么要进行 None
处理。您创建的 CDLL 对象 almost 类似于 ctypes.pythonapi
,除了它不包含用于函数调用或检查异常的 GIL(因为 CDLL 而不是 PyDLL),所以与实际的 C Python API.
交互是没有用的
有人可以向我解释为什么以下 Python 代码有效吗?
import ctypes
import ctypes.util
boblib = ctypes.cdll.LoadLibrary(ctypes.util.find_library("bob_is_your_uncle"))
boblib.cos.argtypes = [ctypes.c_double]
boblib.cos.restype = ctypes.c_double
print(boblib.cos(0)) # This prints out "1.0"
我 1000% 确定我的文件系统上没有 "bob_is_your_uncle" 库。然而,似乎 ctypes 加载了 m
库。为什么会这样?
另外,如果我这样做:print(boblib)
,我得到这个:
<CDLL 'None', handle 7f6a80f6d170 at 0x7f6a7f34d0b8>
CDLL 'None'
是什么意思?
提前致谢。
PS:在我的两个 Python 解释器上执行 --version
我得到:
Python 3.6.5rc1
和 Python 2.7.14+
。上面的代码在两个版本上给出了相同的结果。我的 OS 是 Debian(测试仓库)。
它没有加载数学库。它似乎正在加载 Python 可执行文件本身,其中链接了 cos
。
确实没有名为bob_is_your_uncle
的库,所以find_library
returnsNone
。 (这就是您看到的输出中 None
的来源。)
在 Unix 上,LoadLibrary
逻辑有一个 specific check that translates a None
name to a null pointer for the underlying dlopen
routine. dlopen
has special handling 用于空名称:
If filename is NULL, then the returned handle is for the main program.
事实上,在 Unix 上,ctypes.pythonapi
是 created 和
pythonapi = PyDLL(None)
首先解释为什么要进行 None
处理。您创建的 CDLL 对象 almost 类似于 ctypes.pythonapi
,除了它不包含用于函数调用或检查异常的 GIL(因为 CDLL 而不是 PyDLL),所以与实际的 C Python API.