I am not a big fan of C++, although it's paid my bills for a few years. These days when I cannot use a more modern language, I tend to reach for plain C more often than not. I find its simplicity much more elegant and pleasant. One of the tasks I had to accomplish at one point was interfacing with Windows WMI, which is basically a COM interface. This task is not that difficult, even in plain C. The approach is fairly similar, with a little syntactic difference. Consider for example the code to get a WBEM Locator object in C++: This code in C becomes: Code Editor
All we've really done here is referecing through the lpVtbl struct member, and providing the object itself as the first parameter to the call. This pattern repeats itself throughout the code when replacing C++ with plain C. You can then adapt most C++ WMI sample code to C. So let's see how we'd query WMI in C. . Note that I leave out the error handling for brevity sake, but wherever you see {...} you should take care to free allocated strings and release objects. Querying WMI in plain C
In writing code such as this that uses a lot of allocations and deallocations, I usually find it easier to allocate at point of use, and deallocate immediately, instead of allocating at the top of function and deallocating at the bottom. But your preference may vary. Also note that although this code uses tchars for compatibility reasons, the WMI strings are always wide strings. To invoke methods, it is fairly similar. Following the above pattern, we enumerate instances. Calling methods on WMI instance providers
So that got us a reference to an instance, now we call it. I find it useful to wrap every method invocation in its own C method. Calling a method on an instance
So that's about it. You really can pick up any C++ function and convert them to C easily. About the only other complication may be that you have to use SysAllocString/SysFreeString instead of the _bstr_t type when creating your BSTRs (since _bstr_t is a class).
0 Comments
|
ArchivesCategories
All
|