开发者

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, b开发者_C百科uf, blockSize, offset);
  free(buf);
}

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


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(), ...);


unsigned long i;
void* p = (void*)&i;


It can be cast using following code:

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


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]);

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

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜