Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to cast from unsigned long to void*?

I am trying to pwrite some data at some offset of a file with a given file descriptor. My data is stored in two vectors. One contains unsigned longs and the other chars.

I thought of building a void * that points to the bit sequence representing my unsigned longs and chars, and pass it to pwrite along with the accumulated size. But how can I cast an unsigned long to a void*? (I guess I can figure out for chars then). Here is what I'm trying to do:

void writeBlock(int fd, int blockSize, unsigned long offset){
  void* buf = malloc(blockSize);
  // here I should be trying to build buf out of vul and vc
  // where vul and vc are my unsigned long and char vectors, respectively.
  pwrite(fd, buf, blockSize, offset);
  free(buf);
}

Also, if you think my above idea is not good, I'll be happy to read suggestions.

like image 665
Pirooz Avatar asked Dec 09 '22 07:12

Pirooz


1 Answers

You cannot meaningfully cast an unsigned long to a void *. The former is a numeric value; the latter is the address of unspecified data. Most systems implement pointers as integers with a special type (that includes any system you're likely to encounter in day-to-day work) but the actual conversion between the types is considered harmful.

If what you want to do is write the value of an unsigned int to your file descriptor, you should take the address of the value by using the & operator:

unsigned int *addressOfMyIntegerValue = &myIntegerValue;
pwrite(fd, addressOfMyIntegerValue, sizeof(unsigned int), ...);

You can loop through your vector or array and write them one by one with that. Alternatively, it may be faster to write them en masse using std::vector's contiguous memory feature:

std::vector<unsigned int> myVector = ...;
unsigned int *allMyIntegers = &myVector[0];
pwrite(fd, allMyIntegers, sizeof(unsigned int) * myVector.size(), ...);
like image 61
Jonathan Grynspan Avatar answered Dec 27 '22 20:12

Jonathan Grynspan