Dynamic Unloading of Classes
In my previous post, I did a demo of the factory pattern. In it I showed how to dynamically load classes based on their path. One thing you may have noticed in that demo is that the classes stayed in memory even after the Test VI stopped running. If you missed it, go try it again.
I got the idea for this from Mattias Baudot’s presentation at GDevCon #1. It was about PPLs, but he mentioned this dynamic unloading principle and you can apply it without using PPLs.
Using the code from the previous post, open the Dynamic Unloading Project. Note this project does not contain the Source Interface. This will be important in a minute.
Open dependencies and look at what is in memory. Run the Test Dynamic Unload VI. At the breakpoint, examine what is in memory. You should see the DAQ class show up along with some other libraries. Then resume the breakpoint. Notice that the DAQ class and other libraries leave memory. Use the ring to select the other sources and notice that the same thing happens.
How did we do this? Well when trying to unload classes, you have to change the way you architect your program a little bit. First you have to sequester all the classes in the class hierarchy that you want to unload. What do I mean by this? The rest of your project cannot load these classes into memory or any of their parents. In this case the DAQ, Scope, and DMM were already not part of our project. But we also have to sequester the Source Interface as well. In the factory example, the Source interface was part of our project. How do we change that?
We start by creating a wrapper around the 2 source methods as seen below. We make sure that we remove the Source Interface from the project and we make sure this wrapper is also not part of the project.
Now we can’t this call wrapper directly from our Test Dynamic Unload VI, so what do we do? We can use VI Server.
It might take a little to wrap your head around this. Hopefully playing with the example code will help. The key to remember is that our test VI knows nothing about any of the classes in the class hierarchy. It launches the wrapper using VI server. The wrapper is what loads the classes into memory. When we close it’s reference, it goes out of memory and takes the classes with it.
The hardest part about Object-Oriented Design is setting up the correct class hierarchy and relationships. When you get it right, it makes adding new features a breeze. It’s often as simple as adding a new child class to contain the new functionality. Without the correct hierarchy, you can quickly create a mess. The GOF patterns help, but it can still be tricky to get it right. If you would like some help making sure you are on the right track, give us a call. We’d be glad to talk to you and schedule a code/design review.