使用不带VirtualBox的VirtualBox SDK

时间:2016-06-28 15:20:39

标签: c winapi com virtualbox

我正在尝试使用虚拟盒SDK启动虚拟盒机器。我已经设法使用SDK目录中提供的mscom示例成功完成了此操作,但仅安装了VirtualBox 。 在没有安装VirtualBox的计算机上,这不再有效。

有什么办法可以在不安装整个VirtualBox软件的情况下实现这一目标吗?也许只是注册一个dll或什么?

这是我正在使用的代码(它与SDK提供的代码几乎相同):

int main(int argc, char *argv[])
{
    HRESULT rc;
    IVirtualBox *virtualBox;

    /* Initialize the COM subsystem. */
    CoInitialize(NULL);

    /* Instantiate the VirtualBox root object. */
 /*######## the following line fails with error 0x80040154 (Class not registered) ######## */
    rc = CoCreateInstance(CLSID_VirtualBox,       /* the VirtualBox base object */
                            NULL,                   /* no aggregation */
                            CLSCTX_LOCAL_SERVER,    /* the object lives in a server process on this machine */
                            IID_IVirtualBox,        /* IID of the interface */
                            (void**)&virtualBox);

    if (!SUCCEEDED(rc))
    {
        printf("Error creating VirtualBox instance! rc = 0x%x\n", rc);
        return 1;
    }

    listVMs(virtualBox);

    /* Enable the following line to get a VM started. */
    //testStartVM(virtualBox);

    /* Release the VirtualBox object. */
    virtualBox->Release();

    CoUninitialize();

    return 0;
}

1 个答案:

答案 0 :(得分:0)

在未安装VirtualBox本身时尝试访问VirtualBox VM有什么意义?如果找不到COM对象,CoCreateInstance()将失败并出现REGDB_E_CLASSNOTREG错误(“指定的类未在注册数据库中注册”)。这正是你得到的错误。如果没有安装VirtualBox,你无能为力。并且您不应该尝试单独安装VirtualBox COM对象以满足您的代码。只需处理错误并继续,当时该机器上没有可用的VirtualBox VM。

顺便说一句,如果CoCreateInstance()失败,如果CoUninitialize()成功(您没有检查),则仍需要致电CoInitialize()

int main(int argc, char *argv[])
{
    HRESULT rc;
    IVirtualBox *virtualBox;

    /* Initialize the COM subsystem. */
    rc = CoInitialize(NULL);
    if (FAILED(rc))
    {    
        printf("Error initializing COM! rc = 0x%x\n", rc);
        return 1;
    }

    /* Instantiate the VirtualBox root object. */
    rc = CoCreateInstance(CLSID_VirtualBox,       /* the VirtualBox base object */
                            NULL,                   /* no aggregation */
                            CLSCTX_LOCAL_SERVER,    /* the object lives in a server process on this machine */
                            IID_IVirtualBox,        /* IID of the interface */
                            (void**)&virtualBox);

    if (FAILED(rc))
    {
        if (rc == REGDB_E_CLASSNOTREG)
            printf("VirtualBox not detected! Please install it.\n");
        else
            printf("Error creating VirtualBox instance! rc = 0x%x\n", rc);

        CoUninitialize();
        return 1;
    }

    listVMs(virtualBox);

    /* Enable the following line to get a VM started. */
    //testStartVM(virtualBox);

    /* Release the VirtualBox object. */
    virtualBox->Release();

    CoUninitialize();

    return 0;
}