Proper use of ctypes to call _Py_Mangle?

安稳与你 提交于 2019-12-08 04:18:31

问题


While sitting on a mushroom and contemplating the intricacies of inscribing a function to implement Python's name mangling algorithm, a stupendously better idea came into my noggin. Why not use the recipe already crafted into the language to accomplish such a goal? So I pulled ctypes out of my satchel to help with the endeavor and executed ctypes.pythonapi._Py_Mangle('Demo', '__test'). Lo and behold, an error appeared out of thin air saying OSError: exception: access violation reading 0x00000A65646F00A8 and did not bother to explain the conundrum any more than that.

The full interaction with the interpreter is as follows:

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

Does anyone know what needs to be changed in order to call the mangling function successfully?


回答1:


Thanks to comments by eryksun, the answer to the problem is rather simple:

>>> 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'


来源:https://stackoverflow.com/questions/27926429/proper-use-of-ctypes-to-call-py-mangle

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!