Julia: Is there a way to convert a number into a pointer?

Viewed 199

As the title says, is there a way to convert a number (say a float or interger) that stores an address into a pointer?

For example, in Julia one can convert a pointer into a integer by doing:

data = [1, 2] 
ptr = pointer( data )      # Has type "Ptr{Int64}"
address = UInt64( ptr )    # Has type "UInt64"

How can one reverse these steps to get back the pointer? Say:

ptr = unknownFunction(address) # Has type "Ptr{Int64}"

Alternatively, is there a way to directly change the address held by a pointer? Say one has a pointer with:

Ptr{Int64} @0x0000000036f94110

How can you modify the address it hold to another number, for example 0x000000003ffffff0.

1 Answers

Yes, that it possible, but only if you already know what data lies at that pointer:

julia> arr = [15, 6, 1];

julia> address = UInt(pointer(arr));

julia> unsafe_load(Ptr{Int}(address))
15

For your second question, Julia supports pointer arithmetic. Here, you can add 8 bytes to the pointer of the first element in the array:

julia> unsafe_load(Ptr{Int}(address) + 8)
6

But I would echo other people's reservations about using pointers in Julia. They are only really useful for interoperation with e.g. C, or for doing questionable low-level bithacking tricks.

Related