Get the address of a variable with Ctypes


After skimming the Ctypes API, I couldn´t figure out how to get the address of a C value. For instance, given the type t = Signed.long ptr and a value v of type t is it possible to get v’s address? The closest I could find is raw_address_of_ptr but it does require a pointer.

You can use allocate for that purpose:

# let v = allocate long (Signed.Long.of_int 30);;
val v : Signed.long Ctypes.ptr = Ctypes_static.CPointer <abstr>
# let pv = allocate (ptr long) v;;
val pv : Signed.long Ctypes_static.ptr Ctypes.ptr =
  Ctypes_static.CPointer <abstr>
# !@pv <-@ Signed.Long.of_int 35;;
- : unit = ()
# Signed.Long.to_int !@v;;
- : int = 35

Thank you very much! Is it also possible to get a pointer to an existing C value (allocated in C with malloc) instead of allocating a fresh value through Ctypes.allocate?

Actually, it’s not possible due to how C passes functions’ arguments by value and thus copies them.