Skip to content

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

Open
@certik

Description

@certik

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.

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions