Can't figure out how to do something using ctypes (and maybe struct?)
Steven D'Aprano
steve+comp.lang.python at pearwood.info
Fri Aug 10 20:15:43 EDT 2018
On Fri, 10 Aug 2018 18:40:11 -0400, inhahe wrote:
> I need to make a list of instances of a Structure, then I need to make
> an instance of another Structure, one of the fields of which needs to be
> an arbitrary-length array of pointers to the instances in the list. How
> do I do that?
>
> Just in case it helps, I'll include what I tried that didn't work:
How about simplifying your example to the smallest and simplest example
of the problem? Your example has:
- two functions;
- one method that seems to have become unattached from its class;
- two classes;
- using 12 different fields.
Surely not all of that detail is specific to the problem you are
happening. If you can simplify the problem, the solution may be more
obvious.
It might help to read this: http://sscce.org/
By the way, unrelated to your specific problem but possibly relevant
elsewhere, you have this function:
> def mkVstEvents(events):
> class Events(ctypes.Structure):
> _fields_ = [ ... ]
> return Events( ... )
You might not be aware of this, but that means that every time you call
mkVstEvents, you get a singleton instance of a new and distinct class
that just happens to have the same name and layout.
So if you did this:
a = mkVstEvents( ... )
b = mkVstEvents( ... )
then a and b would *not* be instances of the same class:
isinstance(a, type(b)) # returns False
isinstance(b, type(a)) # returns False
type(a) == type(b) # also False
Each time you call the function, it creates a brand new class, always
called Events, creates a single instance of that class, and returns it.
That is especially wasteful of memory, since classes aren't small.
py> class Events(ctypes.Structure):
... pass
...
py> sys.getsizeof(Events)
508
Unless that's what you intended, you ought to move the class outside of
the function.
class Events(ctypes.Structure):
_fields_ = [ ... ]
def mkVstEvents(events):
return Events( ... )
--
Steven D'Aprano
"Ever since I learned about confirmation bias, I've been seeing
it everywhere." -- Jon Ronson
More information about the Python-list
mailing list