2

I'm trying to add a simple .mp3 file to the iTunes library but my program keeps crashing when I call AddFile(). However, when I call get_Tracks() it returns a valid pointer, so I suppose the pointer to IITLibraryPlaylist is valid. What am I doing wrong?

IiTunes* p_iTunes;
IITLibraryPlaylist* p_Library;
IITOperationStatus* status;
IITTrackCollection* iTrackCollection;

CoInitialize(0);
if (FAILED(CoCreateInstance(CLSID_iTunesApp, NULL, CLSCTX_LOCAL_SERVER, IID_IiTunes, (PVOID *)&p_iTunes))){
    p_iTunes->Release();
    CoUninitialize();
}
else{
    p_iTunes->get_LibraryPlaylist(&p_Library);

    p_Library->get_Tracks(&iTrackCollection); // This works, so I suppose p_Library is valid..
    long trackCount = 0;
    iTrackCollection->get_Count(&trackCount);

    p_Library->AddFile(L"C:\\asd\asd.mp3",&status); // crashes here
}
Puppy
  • 144,682
  • 38
  • 256
  • 465
iakovos
  • 23
  • 3
  • Btw you have error handling done wrong. If `CoCreateInstance()` fails `p_iTunes` will be null and so calling `Release()` will crash your program. – sharptooth May 16 '11 at 12:51

1 Answers1

2

The problem is you pass WCHAR* instead of properly allocated BSTR and that leads to undefined behavior.

You should first allocate a BSTR using SysAllocString() (don't forget to release the string later) or better yet use a wrapper class like ATL::CComBSTR or _bstr_t for managing BSTR lifetime.

Community
  • 1
  • 1
sharptooth
  • 167,383
  • 100
  • 513
  • 979