Question

I have the following code:

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)
{

}

I can not convert "int" to "LONG*". The compiler tells me "'int' can't be converted to 'LONG *'.

I also tried using INT* instead of LONG*, but that also gave me an error.

Can somebody tell me how I can convert int to LONG* or INT*?

Was it helpful?

Solution 2

You don't need to convert anything. LONG* is a pointer to a LONG, and you can assign an int to a LONG. Simply dereference the pointer so you can then assign it:

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

Or safer:

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

Or even:

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

OTHER TIPS

You have to dereference the pointer you pass to openPort to make it work.

*m_OpenPortResult = Open(c);

This way you write to the address where m_OpenPortResult actually points to. This is what you want. You may also want to read something about references in C++. If you are able to (in form of you are the developer of the openPort-function) modify the function, you might use

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

The appropriate call would look like

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

This might fit your needs better since references have several advantages and should be used when there is no explicit reason to use pointers.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top