'Access Violation' in CreateInstance()??
Am working through Andrew Troelsen's "COM and ATL 3.0" and am having a problem when trying to run a C++ client (even the ones that he wrote and distributed with the book), which uses coclasses from a COM object. I have reason to believe that I am seeing this based upon some setting on my system, so I'm hoping that one of you can tell me what I need to do. I'm posting the code from the client (it's from the books CD) so you can see which line I am getting the error on. If anyone can help, I'd appreciate it. Thanks in advance, Ryan
ps - the offending line is commented as such. Look for '@@@@@' :)
Code:
#include "interfaces.h"
#include "iid.h"
#include <iostream.h>
int main()
{
CoInitialize(NULL); // This parameter is reserved, and should be NULL
HRESULT hr;
IClassFactory* pCF = NULL;
ICreateCar* pICreateCar = NULL;
IStats* pStats = NULL;
IEngine* pEngine = NULL;
cout << "*********************************" << endl;
cout << "The Amazing CoCar Client" << endl;
cout << "*********************************" << endl;
// Get the class factory pointer of CoCar:
hr = CoGetClassObject(CLSID_CoCar, CLSCTX_ALL,
NULL, IID_IClassFactory, (void**)&pCF);
// Make a CoCar & get ICreateCar.
// @@@@@ The error is thrown on the following line @@@@@
hr = pCF->CreateInstance(NULL, IID_ICreateCar, (void**)&pICreateCar);
pCF->Release();
if(SUCCEEDED(hr))
{
pICreateCar->SetMaxSpeed(30);
BSTR petName = SysAllocString(L"Shazzam!");
pICreateCar->SetPetName(petName);
SysFreeString(petName);
// Now get IStats
hr = pICreateCar->QueryInterface(IID_IStats, (void**)&pStats);
pICreateCar->Release();
}
if(SUCCEEDED(hr))
{
// Show my car!
pStats->DisplayStats();
hr = pStats->QueryInterface(IID_IEngine, (void**)&pEngine);
}
if(SUCCEEDED(hr))
{
int curSp = 0;
int maxSp = 0;
pEngine->GetMaxSpeed(&maxSp);
do // Zoom!
{
pEngine->SpeedUp();
pEngine->GetCurSpeed(&curSp);
cout << "Speed is: " << curSp << endl;
}while(curSp <= maxSp);
// Gotta convert to char array.
char buff[80];
BSTR bstr;
pStats->GetPetName(&bstr);
WideCharToMultiByte(CP_ACP, NULL, bstr, -1, buff,
80, NULL, NULL);
cout << buff << " has blown up! Lead Foot!" << endl << endl;
SysFreeString(bstr);
if(pEngine) pEngine->Release();
if(pStats) pStats->Release();
}
CoUninitialize();
return 0;
}