2014-02-13 77 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! 

這可能適合你需要更好,因爲引用有幾個優點,應該在沒有明確理由使用指針時使用。

相關問題