如何从unsigned long强制转换为void*
How to cast from unsigned long to void*?
我正试图在给定文件描述符的文件的某些偏移处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()
。
相关文章:
- 为什么这个函数将"const char*"转换为"void* const"而不是"const void*"
- 将尾部调用void(i32,..)位转换为llvm::函数以获取FnAttribute
- 为什么在逗号分隔符上下文中将预增量的结果强制转换为void
- Boost buffer_cast 无法从 void* 转换为 PointerToPodType
- 将通用引用强制转换为可调用的 void 指针,反之亦然
- 为什么在将 void 指针转换为整数指针时出现分段错误
- 在不同的编译器上转换为 void**
- 当我使用 void 函数的返回值(通过强制转换函数指针)时,究竟会发生什么?
- 不能在 if 语句 - c++ 中使用 void func 直接将字符串转换为大写
- 是否可以将已经初始化的变量转换为 void*?
- 错误:从'void*'到'const uint8_t* {aka const unsigned char*}'的转换无效 [-允许]
- 将可变参数模板类型转换为 void,预期')'之前
- 如何在运行时将指向派生类的 void* 正确转换为指向基类的 void*
- 是否强制转换void**并将第一个字节设置为nullptr
- 如何转换 void* 以访问结构的静态数据成员?
- 警告传递"double"以转换"void moveto(int, int)"的 2
- 是否有一种方法可以自动转换void指针的类型
- 在构造函数中强制转换void*并访问值
- 重新解释不带类型标识符的强制转换void
- 强制转换void指针