0

In Python, I am aware certain methods exist in python 3 that can create a new integer from an existing byte array. However, I am looking for a way to create a reference to a byte array, as an integer. Such that, if the reference is changed, then the underlying byte array is also changed.

In C, this would be done like the following:

int main(void) {
  unsigned char bytes[4] = {1, 0, 0, 0};
  int* int_ref = (int*)bytes;
  *int_ref += 59;
  printf("bytes is now %u %u %u %u\n",
                        bytes[0],
                        bytes[1],
                        bytes[2],
                        bytes[3]);
  return 0;
}

The above program prints 60. I am looking for a way to do this in Python.

martineau
  • 119,623
  • 25
  • 170
  • 301
Josh Weinstein
  • 2,788
  • 2
  • 21
  • 38
  • 1
    "However, I am looking for a way to create a reference to a byte array, as an integer." Such a thing does not exist in Python. If you want to work with stuff like that, use C. Python is a purely object-oriented language. Everything is an object. There are no pointers in the language either. – juanpa.arrivillaga Dec 26 '18 at 22:11
  • 1
    Although, there may be something in the `ctypes` module to approximate what you are looking for, this screams XY problem to me. What is it that you are *actually* trying to accomplish? Why can't you just use the `bytearray` when you need an integer? Note, `arr[i]` will return an `int` type (which gets created on the fly). – juanpa.arrivillaga Dec 26 '18 at 22:17
  • @juanpa.arrivillaga I am trying to see if it's possible in python to make a byte code reader, that can read packed, typed data that's stored in binary. However, I am seeing the `struct` module may be more what i am looking for. I guess the reference idea might not be doable for python. – Josh Weinstein Dec 26 '18 at 22:49
  • Actually, that's undefined behavior even in C. To do it legally you have to have an `int` object that is aliased by a `char *`, not the other way around. – Matteo Italia Dec 26 '18 at 22:54

1 Answers1

1

Something along these lines seems close to what you want:

import _ctypes

def di(obj_id):
    """ Reverse of id() function. """
    # from https://stackoverflow.com/a/15012814/355230
    return _ctypes.PyObj_FromPtr(obj_id)

def func(obj_id):
    ba = di(obj_id)
    ba[0] += 50

data = bytearray([1, 0, 0, 0])
func(id(data))

print('bytes is now {} {} {} {}'.format(*data))  # -> bytes is now 51 0 0 0
martineau
  • 119,623
  • 25
  • 170
  • 301