简体   繁体   中英

Can't read memory of a struct allocated by CoTaskMemAlloc

I have the following problem.

I am implementing an IDataObject , which is responsible for passing files to the Clipboard. When I call GetData on my IDataObject it seems to return an empty STGMEDIUM struct with unreadable memory, although I could confirm that the struct was filled with the correct values through a breakpoint. This is my code:

Call to GetData:

FORMATETC dsl_form={//some FORMATETC};
STGMEDIUM *dsl_med = {0};

HRESULT hr;
hr=dsp_in->GetData(&dsl_form, dsl_med);

The GetData-Function:

HRESULT STDMETHODCALLTYPE GetData(FORMATETC *dsp_fmt,STGMEDIUM *dsp_med) {
    int iml_idx=m_lookup_format(dsp_fmt);//Search the FORMATETC-Array for a Format that equals the given Format
    //If no suitable FormatEtc was found, report an error
    if(iml_idx<0){
        return DV_E_FORMATETC;
    }
    //Allocate and fill a new STGMEDIUM structure
    dsp_med=(STGMEDIUM*) CoTaskMemAlloc(sizeof STGMEDIUM);
    dsp_med->tymed=dsc_filedesc[iml_idx].tymed;
    dsp_med->pUnkForRelease=0;
    switch(dsc_filedesc[iml_idx].tymed) {
    case TYMED_HGLOBAL:     dsp_med->hGlobal=m_dup_global_mem(dsc_filecontents[iml_idx].hGlobal);
                            break;
    default:                return DV_E_FORMATETC;
    }

    return S_OK;

This

STGMEDIUM *dsl_med = {0};

HRESULT hr;
hr=dsp_in->GetData(&dsl_form, dsl_med);

copies null dsl_med into function parameter, the function called changes the copy passed to it, but the original null value is unchanged so the pointer on the caller side remains null.

One option would be to change the function signature so that it accepts STGMEDIUM** and alter the rest of the code accordingly. However in this case - when implementing IDataObject::GetData() - you cannot change the signature. If you read MSDN description it explains that the function should only allocate the stuff it assigns to the members of the structure, and the caller has to allocate the structure and optionally free its members.

So you have to pass the address of the struct

STGMEDIUM dsl_med = {0};
object->GetData(&dsl_from, &dsl_med);

and inside the function you just set the structure members.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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