2014-02-13 75 views
3

我有以下代码:C++转换的int * LONG

STDMETHODIMP CWrapper::openPort(LONG* m_OpenPortResult) 
{ 
    string str("test"); 
    const char * c = str.c_str(); 

    m_OpenPortResult=Open(c); //this does not work because "Open" returns an int 

    return S_OK; 
} 

int Open(const char* uKey) 
{ 

} 

我不能转换为 “int” 为 “LONG *”。 编译器告诉我“‘诠释’不能转换为‘LONG *’。

我也用INT *而不是LONG *试过了,但也给了我一个错误。

有人可以告诉我怎么能转换为int长*或* INT?

回答

1

你不需要任何转换。LONG*是一个指向LONG,你可以指定一个intLONG,只需取消引用指针,所以你然后可以指定它:

*m_OpenPortResult = Open(c); // <-- note the * 

或更安全:

if (!m_OpenPortResult) return E_POINTER; 
*m_OpenPortResult) = Open(c); 

甚至:

LONG ret = Open(c); 
if (m_OpenPortResult) *m_OpenPortResult = ret; 
4

你必须取消引用指针传递给openPort,使其工作。

*m_OpenPortResult = Open(c); 

这样你就可以写到m_OpenPortResult实际指向的地址。这是你想要的。 您可能还想阅读关于C++中引用的内容。如果你能(在你的形式是openPort - 函数的开发者)修改功能,您可以使用

STDMETHODIMP CWrapper::openPort(LONG &m_OpenPortResult) 
{ 
    // code... 
    m_OpenPortResult = Open(c); 
    return S_OK; 
} 

相应的呼叫看起来像

LONG yourResult; 
wrapperInstance.openPort(yourResult); // without & before! 

这可能适合你需要更好,因为引用有几个优点,应该在没有明确理由使用指针时使用。

相关问题