Loading an Object from a Resource

Loading an object from a resource, or from some other location in memory, is done in a similar fashion to loading an object from a file. (See Loading Objects.) In this case, however, the wszName, guidObject, and wszFileName members of the DMUS_OBJECTDESC structure are irrelevant. Instead you must obtain a pointer to the block of memory occupied by the object, and its size, and put these in the pbMemData and llMemLength members respectively of the DMUS_OBJECTDESC structure. You must also set the DMUS_OBJ_MEMORY flag in the dwFlags member.

Note that the memory cannot be released once IDirectMusicLoader::GetObject has been called, because the loader keeps the pointer to the memory internally, to facilitate caching data. If you want to clear it out, call IDirectMusicLoader::SetObject with the same DMUS_OBJECTDESC descriptor, but with NULL in pbMemData. This is not an issue with loading from a resource, because resource memory is not freed.

The following function loads a MIDI file from a resource into a segment:

HRESULT LoadMidi(HMODULE hMod, WORD ResourceID)
{
    HRESULT              hr;
    DMUS_OBJECTDESC      ObjDesc;
    IDirectMusicSegment* pSegment = NULL; 
 
    HRSRC hFound = FindResource(hMod, 
            MAKEINTRESOURCE(ResourceID), RT_RCDATA);
    HGLOBAL hRes = LoadResource(hMod, hFound);
 
    ObjDesc.dwSize = sizeof(DMUS_OBJECTDESC);
    ObjDesc.guidClass = CLSID_DirectMusicSegment;
    ObjDesc.dwValidData = DMUS_OBJ_CLASS | DMUS_OBJ_MEMORY;
    ObjDesc.pbMemData = (BYTE *) LockResource(hRes);
    ObjDesc.llMemLength = SizeofResource(hMod, hFound);
 
    hr = m_pDXPerformance->m_pLoader->GetObject(
            &ObjDesc, IID_IDirectMusicSegment, 
            (void**) &m_pSegment );
 
    return hr;
}