The MacView

Virtual Instrumentation from a Mac perspective

Thursday, May 06, 2010

How To Automate Creating Large Enums

I was creating some VIs to call the OS to get system colors directly when I ran into an annoyance. The OS defines a long list of constants (in this case kThemeBrush* in Appearance.h on the Mac). I wanted an enum in my VI API to make code calling my VI more readable (right click -> create constant on the enum terminal creates an enum constant on the diagram). There were 62 enum values to enter. This was not something I wanted to type one by one into the enum control. So I came up with a way to automate much of the creation.

First I searched for all lines in Appearance.h that contain kThemeBrush and a number. I took those lines and pasted them into a string constant and then wrote some code to parse out the constant name and value (see diagram below).



So what does this diagram do? First I use vi.lib/AdvancedString/Normalize End Of Line.vi to make sure the line endings in the string are the LabVIEW platform line ending (\r on the Mac). I then use Spreadsheet String To Array primitive to parse the string into lines (one of my favorite text parsing tricks in LabVIEW). Then for each line I get the part before the equals (name of the constant) and then I get the part between the equals and the comma (constant value).

I then copy the Ring to my VI, right click on it and select Replace and replace it with an enum. LabVIEW preserves all the strings. However, to get the appropriate value (enums by default use their (zero based) index as their value) I use the output array.

The front panel of the VI has a Ring (not enum because you can't write the strings to an enum on a running VI). The constant names are written to the Ring values (Strings[]) and we output an array of the constant values. We right click on the array control and select Data Operations -> Copy Data. Then right click on the array constant in the diagram below and select Data Operations -> Paste Data.



This diagram converts the enum values to the constants from the header.

I did this for two separate API calls (Theme Text and Theme Brush), each with their own set of constants. More reliable and much faster than doing it by hand.

Labels: , ,

The views expressed on this website/weblog are mine alone and do not necessarily reflect the views of my employer.