Nur so geradlinig, scheint in Python nicht zu funktionieren. < /p>
import ctypes
class cA(ctypes.Structure):
_fields_ = [("a", ctypes.c_ubyte)]
def __init__(self):
super().__init__()
self.c = 3
z = cA.from_buffer_copy(b'0')
print (z)
print (z.c)
print (dir(z))
< /code>
Traceback (most recent call last):
File "polymorph.py", line 12, in
print (z.c)
AttributeError: 'cA' object has no attribute 'c'
< /code>
So ctypes.Structure factory classmethod from_buffer_copy() doesn't seem to use the default constuctor __init__ .
Is this correct and intended by cytpes.Strucutre?
Ok even if not trying to workaround this, by overwriting the class method from_buffer_copy raises another issue.
Like adding to class cA:
@classmethod
def from_buffer_copy(cls,buffer, offset=0):
#obj = super().from_buffer_copy(b'2',offset)
obj = cls.from_buffer_copy(b'2',offset)
obj.__init__()
return obj
< /code>
Traceback (most recent call last):
File "polymorph.py", line 17, in
z = cA.from_buffer_copy(b'0')
File "polymorph.py", line 13, in from_buffer_copy
obj = cls.from_buffer_copy(b'2',offset)
File "polymorph.py", line 13, in from_buffer_copy
obj = cls.from_buffer_copy(b'2',offset)
File "polymorph.py", line 13, in from_buffer_copy
obj = cls.from_buffer_copy(b'2',offset)
[Previous line repeated 996 more times]
RecursionError: maximum recursion depth exceeded
< /code>
This creates a RecursionError, because same class method is called again and again, but Structure.from_buffer_copy can't be called either, because it lacks the fields.
Using super() above doesn't helps either. It raises an Attribute Error:
Traceback (most recent call last):
File "polymorph.py", line 17, in
z = cA.from_buffer_copy(b'0')
File "polymorph.py", line 12, in from_buffer_copy
obj = super().from_buffer_copy(b'2',offset)
AttributeError: 'super' object has no attribute 'from_buffer_copy'
< /code>
This seems to be similar to Using super with a class method
Looks like a special python 3 thing either.
So cytypes.Structure seems to be a real special kind of class.
As doing the same with regular python class is no issue.
Like:
import ctypes
class A:
def __init__(self):
self.a = "Tex"
@classmethod
def factory(cls):
return cls()
class B(A):
def __init__(self):
super().__init__()
self.b = "bTex"
z = B.factory()
print (z)
print (z.b)
print (dir(z))
< /code>
So ... Is there a way to mix ctypes.Structure with regular python class fields or better just don't do it and better embed ctypes.Structure inside other regular classes for this just to work around this?
Ist es möglich, CTypes.struktur mit regelmäßigen Pythonfeldern zu mischen? ⇐ Python
-
- Similar Topics
- Replies
- Views
- Last post
-
-
Ist es möglich, CTypes.struktur mit regelmäßigen Pythonfeldern zu mischen?
by Anonymous » » in Python - 0 Replies
- 5 Views
-
Last post by Anonymous
-