将定义的宏字符串转换为void*

convert defined macro string to void*

本文关键字:void 转换 字符串 定义      更新时间:2023-10-16

我定义了一个宏,如下所示:

#define SOME_STRING  "some_string"

,并且存在一个类型为void*的字段。因此,为了将"some_string"的地址分配给该字段,我这样做了:

boxFixtureDef.userData = static_cast<void*>(SOME_STRING);

MVS 2012没有报错,但Xcode和g++报告错误:invalid static_cast from type 'const char [12]' to type 'void*'。怎么了?如何解决这个问题?

使用const_cast删除constness。Static_cast不能改变变量的常量。

#include <iostream>
#define MACRO_TEXT "macro-text"
int main()
{
    void *ptr = const_cast<char*>(MACRO_TEXT);
    std::cout << ptr << std::endl;
    return 0;
}

(你不需要显式地将char*转换为void*。它将隐式地完成)

小心些而已。你不允许修改userData中的值,因为原始指针是const char[],在这种情况下,你只能从userData中读取值

这解决了,但我不知道这有多正确:

boxFixtureDef.userData = reinterpret_cast<void*>(const_cast<char*>(SOME_STRING);

static_cast不能抛弃constness。为此,需要const_cast:

static_cast<void*>("something"); // This doesn't compile
static_cast<const void*>("something"); // This does
const_cast<void *>(static_cast<const void*>("something")); // This does, too.

同样,指向void *的指针的隐式转换不影响cv限定符:

void *something = "something"; // This doesn't compile
void *something2 = const_cast<char *>("something"); // This does; the char * from the cast is implicitly converted
void *something3 = const_cast<void *>(static_cast<const void*>("something")); // This does, too, but is more verbose.

但是,如果有人试图修改结果指针指向的内容,那就是未定义行为。因此,如果boxFixtureDef.userData指向的内容可以修改,则不应该这样做。如果不是,为什么不把它改成const void *呢?

只用(void *)(SOME_STRING)