【发布时间】:2015-01-13 16:09:33
【问题描述】:
当我坐在蘑菇上思考编写一个函数来实现 Python 的名称修饰算法的复杂性时,我的脑海中浮现出一个更好的主意。为什么不使用已经在语言中制作的配方来实现这样的目标呢?所以我把ctypes从我的书包里拿出来帮助完成这项工作并执行了ctypes.pythonapi._Py_Mangle('Demo', '__test')。瞧,凭空出现了一个错误,说 OSError: exception: access violation reading 0x00000A65646F00A8 并且没有费心解释这个难题。
与解释器的完整交互如下:
Python 3.4.2 (v3.4.2:ab2c023a9432, Oct 6 2014, 22:16:31) [MSC v.1600 64 bit (AMD64)] on win32
Type "copyright", "credits" or "license()" for more information.
>>> import ctypes
>>> ctypes.pythonapi._Py_Mangle('Demo', '__test')
Traceback (most recent call last):
File "<pyshell#1>", line 1, in <module>
ctypes.pythonapi._Py_Mangle('Demo', '__test')
OSError: exception: access violation reading 0x00000A65646F00A8
有谁知道需要改变什么才能成功调用 mangling 函数?
【问题讨论】:
-
pythonapi是PyDLL的一个实例,它是CDLL的一个子类,它在函数指针上设置一个标志以防止在调用期间释放全局解释器锁(GIL)。否则默认参数转换和结果类型与CDLL相同。因此您需要定义类型:ctypes.pythonapi._Py_Mangle.argtypes = [ctypes.py_object, ctypes.py_object];ctypes.pythonapi._Py_Mangle.restype = ctypes.py_object。 -
仅供参考,如果您的代码必须在 PyPy、Jython 或 IronPython 上运行,这将无济于事。真的应该有一个
sys.name_mangle或inspect.name_mangle来为你做这件事。 -
@eryksun:有功能请求或 PEP 吗?或者至少是
python-ideas讨论?
标签: python exception python-3.x ctypes name-mangling