Listing 1
program.cpp // This is the main program #include <dlfcn.h> int main(int argc, char** argv) { // Open the libLowPass shared library void* library = dlopen("libLowPass.so", RTLD_NOW); // Get the loadFilter function, for loading objects void* loadFilter = dlsym(library, "loadFilter"); // Get a new filter object void* filter_vp = (*loadFilter)(); Filter* filter = reinterpret_cast<Filter*>(filter_vp); // Gets a frame of audio data, and processes it through // the LowPassFilter object. char* data = getAudio(); filter->processAudio(data); // Get the deleteFilter function and delete the filter void* deleteFilter = dlsym(library, "deleteFilter"); (*deleteFilter)(filter_vp); } //filter.cpp // The superclass, known to the program that is doing the dynamic loading. class Filter { public: virtual void processAudio(char* data) = 0; }; // The LowPassFilter class can be compiled into a shared object // library, along with library.cpp, and then loaded by the program. class LowPassFilter : public Filter { public: virtual void processAudio(char* data) { /* Process the received audio data */ } }; //library.cpp extern "C" { // loadFilter function creates new LowPassFilter object and returns it. void* loadFilter(void) { return reinterpret_cast<void*>(new LowPassFilter); } // The deleteFilter function deletes the LowPassFilter that is passed // to it. This isn't a very safe function, since there's no // way to ensure that the object provided is indeed a LowPassFilter. void deleteFilter(void* obj) { delete reinterpret_cast<LowPassFilter*>(obj); } }