2

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?

Noctis Skytower
  • 21,433
  • 16
  • 79
  • 117
  • 2
    `pythonapi` is an instance of `PyDLL`, which is a subclass of `CDLL` that sets a flag on function pointers to prevent releasing the global interpreter lock (GIL) during a call. Otherwise the default argument conversions and result type are the same as `CDLL`. Thus you need to define the types: `ctypes.pythonapi._Py_Mangle.argtypes = [ctypes.py_object, ctypes.py_object];` `ctypes.pythonapi._Py_Mangle.restype = ctypes.py_object`. – Eryk Sun Jan 13 '15 at 17:30
  • 2
    FYI, this won't help if your code has to run on PyPy, Jython, or IronPython. Really there should be a `sys.name_mangle` or `inspect.name_mangle` to do this for you. – Eryk Sun Jan 13 '15 at 17:36
  • 1
    @eryksun: Is there a feature request or PEP for that? Or at least a `python-ideas` discussion? – Kevin Jan 13 '15 at 19:07

1 Answers1

3

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'
Community
  • 1
  • 1
Noctis Skytower
  • 21,433
  • 16
  • 79
  • 117