I want to mimic a piece of C code in Python with ctypes, the code is something like:
typedef struct {
int x;
int y;
} point;
void copy_point(point *a, point *b) {
*a = *b;
}
in ctypes it's not possible to do the following:
from ctypes import *
class Point(Structure):
_fields_ = [("x", c_int),("y", c_int)]
def copy_point(a, b):
a.contents = b.contents
p0 = pointer(Point())
p1 = pointer(Point())
copy_point(p0,p1)
as the contents
still is a Python ctypes Structure object, that is managed as a reference itself.
An obvious workaround would be to manually copy each field (that is represented as immutable python int's), but that doesn't scale with more complex structures. Also, it would need to be done recursively for fields that are not basic, but structured types.
My other option is to use memmove
and copy the objects as if they were buffers, but that seems very error prone (as Python is dynamically typed it would be too easy to use it with objects of distinct type and size, leading to memory corruption or segmentation faults)...
Any suggestions?
Edit:
I could also use a fresh new copy of the structure, so maybe this could be useful:
import copy
p0 = Point()
p1 = copy.deepcopy(p0) #or just a shallow copy for this example
but I don't know if there might be some kind of bizarre behaviours copying ctypes proxys as if they were regular Python objects...