pythonexceptionpython-3.xctypesname-mangling

Proper use of ctypes to call _Py_Mangle?


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?


Solution

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