如何从unsigned long强制转换为void*

How to cast from unsigned long to void*?

本文关键字:转换 void unsigned long      更新时间:2023-10-16

我正试图在给定文件描述符的文件的某些偏移处pwrite一些数据。我的数据存储在两个向量中。一个包含unsigned long s,另一个包含char s。

我想建立一个void *,它指向代表我的unsigned long s和char s的位序列,并将其与累积大小一起传递给pwrite。但是如何将unsigned long转换为void*呢?(我想我可以算出来)。下面是我要做的:

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

另外,如果你认为我上面的想法不好,我很乐意听取你的建议。

不能有意义地将unsigned long转换为void *。前者是一个数值;后者是未指定数据的地址。大多数系统将指针实现为具有特殊类型的整数(包括您在日常工作中可能遇到的任何系统),但类型之间的实际转换被认为是有害的。

如果你想做的是将unsigned int的值写入你的文件描述符,你应该通过使用&操作符来获取该值的地址:

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

可以循环遍历vector或数组,然后逐个写入它们。或者,使用std::vector的连续内存特性批量写入它们可能会更快:

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;

可以使用以下代码强制转换:

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

像这样:

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

书写大小为v1.size() * sizeof(unsigned long)v2.size()