Question

I'm very new to anything involving Component Object Model, and I'm wondering if this method of managing calls to CoInitalize/CoUninitalize makes sense:

COM.hpp:

#pragma once

namespace WindowsAPI { namespace ComponentObjectModel {

class COM
{
    COM();
    ~COM();
public:
    static void Setup();
};

}}

COM.cpp:

#include <Windows.h>
#include "COM.hpp"

namespace WindowsAPI { namespace ComponentObjectModel {

COM::COM()
{
    if (CoInitializeEx(NULL, COINIT_APARTMENTTHREADED) != S_OK) throw std::runtime_error("Couldn't start COM!");
}

COM::~COM()
{
    CoUninitialize();
}

void COM::Setup()
{
    static COM instance;
}

}}

Then any component that needs COM just calls COM::Setup() and forgets about it.

Does this make sense or am I breaking any "rules" of COM?

Was it helpful?

Solution

I don't believe that static storage variables are destroyed on dll unload, but you shouldn't be using this from a dll anyway.

I generally do something similar, but I don't bother with a function static, I just make the ctor/dtor public and drop an instance in my main():

int WINAPI wWinMain(...) {
    Com::ComInit comInitGuard;
    ...
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top