【问题标题】:Proper use of ctypes to call _Py_Mangle?正确使用 ctypes 来调用 _Py_Mangle?
【发布时间】: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 函数?

【问题讨论】:

  • pythonapiPyDLL 的一个实例,它是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_mangleinspect.name_mangle 来为你做这件事。
  • @eryksun:有功能请求或 PEP 吗?或者至少是python-ideas 讨论?

标签: python exception python-3.x ctypes name-mangling


【解决方案1】:

感谢eryksun的cmets,问题的答案相当简单:

>>> from ctypes import pythonapi, py_object
>>> py_mangle = pythonapi._Py_Mangle
>>> py_mangle.argtypes = py_object, py_object
>>> py_mangle.restype = py_object
>>> py_mangle('Demo', '__test')
'_Demo__test'

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2011-12-15
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-07-28
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多