c++ - 如何从 unsigned long 转换为 void*?

标签 c++ file-io casting

我正在尝试在具有给定文件描述符的文件的某个偏移处pwrite 一些数据。我的数据存储在两个 vector 中。一个包含 unsigned long 和其他 char

我想构建一个 void * 指向代表我的 unsigned longchar 的位序列,并将它传递给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(), ...);

关于c++ - 如何从 unsigned long 转换为 void*?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/6893195/

相关文章:

c++ - 两个类的 "Addition"

c++ - 在 Linux 中为 c++ 使用 gprof -f 选项

java - 像 PHP 中的文件写入/读取功能

security - 在delphi7中安全删除文件

java - double 型比较器

C#:枚举是否在上下文中适本地将自己转换为字符串或整数

c++ - 为什么动态内存分配在 600MB 后会失败?

c++ - 在 GDB pretty-print 中显示特定的 std::vector 元素

Perl 如何从作为数组元素的文件句柄中读取一行

C++显式复制构造函数?