Tuesday, 7 July 2009

Using the Enumerations provided by VirtualBox's SDK with Python and XPCOM

Because this was surprisingly difficult to find out - thanks to Benjamin who provided the answer :o)

So... the VirtualBox SDK allows you to control VirtualBox programmatically. In particular from a selection of languages using either XPCOM or SOAP. I've been working with Python using the XPCOM method, which looks a bit like this...

vbox = xpcom.components.classes["@virtualbox.org/VirtualBox;1"].createInstance()
session = xpcom.components.classes["@virtualbox.org/Session;1"].createInstance()

default_id = "00000000-0000-0000-0000-000000000000"
mach = vbox.createMachine("my_new_vm_name", "Ubuntu", None, default_id)

All good so far... and indeed for quite a long while. Still, this last week Hobnob and I have been pushing the SDK a little bit futher and discovered a need to use some of the built in enumerations. For example, to register a hard disk within VirtualBox using the SDK you'll need the openHardDisk() method provided by the IVirtualBox interface. This takes, as one of it's parameters an enum AccessMode (which does the obvious), the documentation tells you that this is provided in VirtualBox.idl and looks something like this:

Looking good? Well almost. It's just a shame that there's no good examples around to show you how to do this. After some experimentation, Hobnob and I settled for looking up the values and then dropping them into the code I was trying to write:

AccessMode_ReadWrite = 2
hd = vbox.openHardDisk("/vm_disks/mydisk.vdi", AccessMode_ReadWrite, False, "", False, "")

Clearly this is not the way this was meant to be done. So how do you use the built in enums? Answer... like this:

ifaces = xpcom.components.interfaces
hd = vbox.openHardDisk("/vm_disks/mydisk.vdi", ifaces.AccessMode.ReadWrite, False, "", False, "")

Easy when you know how, huh :) So now I can remove these lines from my code:

AccessMode_ReadWrite = 2
HardDiskType_Immutable = 1
HardDiskVariant_Standard = 0

And replace them with:


And it turns out I wasn't using HardDiskType_Immutable anymore anyway :) You never know what you'll find with a quick code tidy.

No comments:

Post a Comment


Related Posts Plugin for WordPress, Blogger...