How to cast from unsigned long to void *?

I am trying to pwrite some data with some file offset with a given file descriptor. My data is stored in two vectors. One contains an unsigned long , and the other contains char s.

I was thinking of creating a void * that points to a sequence of bits representing my unsigned long and char s, and passes it to pwrite along with the accumulated size. But how can I apply an unsigned long to void* ? (I think then I can find the characters). Here is what I am 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 idea is higher, I will be happy to read the suggestions.

+4
source share
4 answers

You cannot purposefully apply an unsigned long to void * . The first is a numerical value; the last is the address of the unspecified data. Most systems implement pointers as integers with a special type (which includes any system that you are likely to encounter in everyday work), but the actual conversion between types is considered harmful.

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

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

You can scroll your vector or array and write them one by one with this. Alternatively, they can be written more quickly using the std::vector function of continuous memory:

 std::vector<unsigned int> myVector = ...; unsigned int *allMyIntegers = &myVector[0]; pwrite(fd, allMyIntegers, sizeof(unsigned int) * myVector.size(), ...); 
+6
source
 unsigned long i; void* p = (void*)&i; 
+3
source

It can be used with the following code:

 unsigned long my_long; pwrite(fd, (void*)&my_long, ...); 
+2
source

Like this:

 std::vector<unsigned long> v1; std::vector<char> v2; void * p1 = reinterpret_cast<void*>(&v1[0]); void * p2 = reinterpret_cast<void*>(&v2[0]); 

Enter the sizes v1.size() * sizeof(unsigned long) and v2.size() .

0
source

All Articles