简体   繁体   English

将指针转换为LPVOID *

[英]cast pointer to pointer as LPVOID*

I have following code: 我有以下代码:

IShellLink* psl;
HRESULT hres = CoCreateInstance(
    CLSID_ShellLink, 
    NULL, 
    CLSCTX_INPROC_SERVER, 
    IID_IShellLink, 
    (LPVOID*)&psl);

It is correctly compiled. 它已正确编译。 But I need to replace (LPVOID*)&psl by *_cast . 但是我需要用*_cast替换(LPVOID*)&psl What cast I must use? 我必须使用哪种演员表?

static_cast<LPVOID*>(&psl) generates an error (in MSVC 2013). static_cast<LPVOID*>(&psl)生成错误(在MSVC 2013中)。

Will it be correct to use reinterpret_cast<LPVOID*>(&psl) ? 使用reinterpret_cast<LPVOID*>(&psl)是否正确?

Yes, reinterpret_cast is the correct choice. 是的,reinterpret_cast是正确的选择。 Usually, the conversion from a type* to a void* should be done implicit, while the conversion from a void* to a type* should be done with a static_cast. 通常,从type *到void *的转换应该隐式完成,而从void *到type *的转换应该使用static_cast完成。 But in your case you're converting from a type** to a void**, which leaves you no choice but to use a reinterpret_cast. 但是在您的情况下,您正在从类型**转换为无效**,这让您别无选择,只能使用reinterpret_cast。 It is still somewhat "safer" than a c-style cast though, because you cannot cast away constness. 但是,它仍然比c样式强制转换“更安全”,因为您不能放弃constness。

I think you may have to use the reinterpret_cast, as the CoCreateInstance function's last parameter is used for output purposes. 我认为您可能必须使用reinterpret_cast,因为CoCreateInstance函数的最后一个参数用于输出目的。 See this link: https://msdn.microsoft.com/en-us/library/windows/desktop/ms686615(v=vs.85).aspx 请参阅此链接: https : //msdn.microsoft.com/zh-cn/library/windows/desktop/ms686615(v=vs.85).aspx

So whether you do a C-Style cast or use the reinterpret_cast, the function just wants to put a pointer value into your variable "psl" after making an object in heap. 因此,无论您执行C-Style强制转换还是使用reinterpret_cast,该函数都只想在将对象放入堆之后将指针值放入变量“ psl”中。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM