You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

为何可将整数转为void*指针,却无法转换CString?

问题描述

参考一段可正常运行的代码,尝试用相同方法处理CString时遇到问题。原代码可通过reinterpret_cast将整数转为void*作为线程参数:

void **pParam = new void*[2];
pParam[0] = reinterpret_cast<void*>(this);
pParam[1] = reinterpret_cast<void*>(iTrayNumber);
_beginthreadex(NULL, 0, &CInspectionDone::InspectionDoneThread, reinterpret_cast<void*>(pParam), 0, NULL);

但对CString执行相同转换时:

CString strTest = _T("Hello");
void **pParam = new void*[2];
pParam[0] = reinterpret_cast<void*>(this);
pParam[1] = reinterpret_cast<void*>(strTest);

出现编译错误:

1>d:\v4\apps\serialcomm.cpp(160) : error C2440: 'reinterpret_cast' : cannot convert from 'CString' to 'void *'
1>        Conversion requires a constructor or user-defined-conversion operator, which can't be used by const_cast or reinterpret_cast

想知道:是否本质上无法将CString转为void*?或是因为指针本质为整数才允许转换整数?求相关解释。

问题解答
  • 整数能转void*的原因:reinterpret_cast允许整数类型和指针类型之间的转换(只要整数位宽足够容纳指针),指针本身的底层存储就是整数形式的内存地址,所以这种转换是C++标准允许的底层位模式转换。

  • CString不能直接转void*的原因:CString是一个类对象,它包含字符串数据、长度等成员变量,不是单个的地址或整数。reinterpret_cast只能处理基础类型(比如指针、整数)之间的底层转换,不会调用类的构造函数或用户定义的转换运算符——而把类对象转成指针需要明确的转换逻辑,这是reinterpret_cast做不到的,所以编译报错。

  • 正确传递CString给线程的方法:传递CString对象的指针,而不是对象本身:

    CString strTest = _T("Hello");
    void **pParam = new void*[2];
    pParam[0] = reinterpret_cast<void*>(this);
    pParam[1] = reinterpret_cast<void*>(&strTest); // 传递对象地址
    

    注意:要保证strTest的生命周期覆盖线程运行周期,若为临时对象,建议用new在堆上分配CString,线程结束后再释放,避免出现悬空指针。

内容的提问来源于stack exchange,提问作者Sin Han Jinn

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.10 07:35:21