3

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
    What are you trying to accomplish with pointers in Julia? Pointers are not really a Julia thing, and arbitrarily changing pointers is quite unsafe. Does https://stackoverflow.com/a/59126098/5075720 answer your question? – PaSTE Jun 10 '21 at 21:07
  • 1
    Don't do this. The fact that C can makes C noticeably slower, because it prevents LLVM from moving things around. – Oscar Smith Jun 11 '21 at 02:47
  • 3
    Did you try `Ptr{Int64}(address)`? Still, consider carefully if you should be using pointers at all. – DNF Jun 11 '21 at 06:55
  • @PasTE: The link provides a lot information on how to create a pointer, but nothing on how to revert the process. Still it was helpful, thanks! – snake_man_jim Jun 12 '21 at 17:33
  • @ DNF: This works! I can do: `Ptr{Int64}(Int64(pointer(a))` and it returns the same pointer as `pointer(a)`. Thanks! – snake_man_jim Jun 12 '21 at 17:34

1 Answers1

2

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.

Jakob Nissen
  • 1,981
  • 7
  • 7