1

I'm trying to force Python 2.7 to print a formatted string for a ctypes POINTER(<type>). I figured I'll write a class that inherits from POINTER and overload __str__. Unfortunately running this piece of code:

from ctypes import *

pc_int = POINTER(c_int)
class PInt(pc_int):
    def __str__(self):
        return "Very nice formatting ", self.contents

print pc_int(c_int(5))
print PInt(c_int(5))

fails with such exception

$ python playground.py
<__main__.LP_c_int object at 0x7f67fbedfb00>
Traceback (most recent call last):
  File "playground.py", line 9, in <module>
    print PInt(c_int(5))
TypeError: Cannot create instance: has no _type_

Does anyone know how to cleanly achieve the anticipated effect or what this exception means?

There's only 1 google search result for "TypeError: Cannot create instance: has no type" and it isn't that helpful.

Thanks!

1 Answer 1

3

The problem is that the ctypes metaclass used to implement POINTER and related classes looks directly in the class dictionary for special fields like _type_, and therefore can't handle inherited special fields.

The fix is simple:

pc_int = POINTER(c_int)
class PInt(pc_int):
    _type_ = c_int # not pc_int
    ...
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.