In the previous part I have explain what are classes and also shown a simple example. In this part, we will look at how we may use classes with SolidWorks API.
Using SolidWorks API with Classes
When dealing with assemblies in SolidWorks API, we often find ourselves dealing with multiple parameters of each individual part. We also need to switch between using the methods from the “Component2” and “ModelDoc2” interfaces depending on the context that we are editing the part in.
With all these requirements, it is a good idea to create a class to deal with all of it.
For this example, we would like to create a macro that will find all large volume parts in an assembly. It will then list out the file name and path as well as their mass.
Defining the Class
In our custom class for this example, we want it to contain the following parameters:
- Component2 object
- ModelDoc2 object
- File name
- File path
- Mass
- Volume
In the example class below, we first declare all the variables. These include the Component2 and ModelDoc2 objects.
Then we also create an initialize function that takes in a Component2 object. Note: For C# and C++ languages, there are special constructors that you can use to initialize the values inside the class.
For VBA however, it is a bit more manual where you need to instantiate and construct the class object separately.
Now whenever we create a new object in the main program using this class, we will have to run the initialize function to populate all the variables in our class with values.
Inside the function are the code that does all that for us. This will help keep our main program neat and tidy.
Using the Class in the Main Program
In the main program, we have some simple code to assign all the components in the assembly into the variable “allComponents” using “AssemblyDoc::GetComponents”.
We then run a for loop to iterate through all the components in our assembly.
Within the for loop, we first declare a variable to store the individual “Component2” object for each iteration. Then we declare a new variable to store our swComp class object. After we declare a new class object, we must set a new class object to our variable. This will initialize our object with the default empty values, but more importantly allocate memory to store the object.
We now initialize the object using the component object. When the component object is passed into the initialize function, all the variables for our swComp class object are populated with the values. We can now access them using the dot operator.
Summary
In conclusion, classes are a simple to use tool with immense capabilities to help simplify and organize your programs. As seen from the example above, we are able to avoid declaring many variables and functions in our main program by using classes.