Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

pointer(x) doesn't update x in CPython #670

Open
Tracked by #1575
certik opened this issue Jun 21, 2022 · 1 comment
Open
Tracked by #1575

pointer(x) doesn't update x in CPython #670

certik opened this issue Jun 21, 2022 · 1 comment

Comments

@certik
Copy link
Contributor

certik commented Jun 21, 2022

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.

@certik
Copy link
Contributor Author

certik commented Jun 21, 2022

To fix this issue, let's add the workaround using a numpy array as a test in our integration_tests, using cpython, llvm and c.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

1 participant