In CPython, when we do:
x: i32
x = 5
y: CPtr[i32] = pointer(x, i32)
And then we pass y into C, and C updates "*y", it does not update x.
This is caused by this line:
|
return ctypes.cast(ctypes.pointer(ctypes.c_int32(x)), |
Which wraps the variable
x into a
ctypes.c_int32(x) wrapper. In that wrapper, the value gets updated, but this updated value will not propagate back to
x itself, since in Python the semantics does not allow that.
If we want to support this feature, we would need to do something like this:
from ltypes import Target, target
x: Target[i32] = target(i32)
x = 5
y: CPtr[i32] = pointer(x, i32)
And the target creates the wrapper class, that overloads the = operator (if it is allowed) and x=5 then puts it into the wrapper. Then pointer(x, i32) should be able to update this wrapper. This is really quite hackish, and almost does not seem worth doing.
A better approach might be to use a numpy array, and make CPtr point to the first element. Then I think the first element should update.
All these C interop things are meant to be used when interacting with C, and one can create a small Python function to hide this in it. And if we have the freedom to design the C interface, it's better to return the integer as a result of the function, then there is no problem.
In CPython, when we do:
And then we pass
yinto C, and C updates "*y", it does not updatex.This is caused by this line:
lpython/src/runtime/ltypes/ltypes.py
Line 195 in f49908e
Which wraps the variable
xinto actypes.c_int32(x)wrapper. In that wrapper, the value gets updated, but this updated value will not propagate back toxitself, since in Python the semantics does not allow that.If we want to support this feature, we would need to do something like this:
And the
targetcreates the wrapper class, that overloads the=operator (if it is allowed) andx=5then puts it into the wrapper. Thenpointer(x, i32)should be able to update this wrapper. This is really quite hackish, and almost does not seem worth doing.A better approach might be to use a numpy array, and make CPtr point to the first element. Then I think the first element should update.
All these C interop things are meant to be used when interacting with C, and one can create a small Python function to hide this in it. And if we have the freedom to design the C interface, it's better to return the integer as a result of the function, then there is no problem.