I need to initialize multiple instances of the same library that has global variables. The naive way of LibraryFunctionLoad
ing functions multiple times doesn't work since the global variables are shared across all loaded functions. How do I confine the global variables to each instance?
Consider the minimal example:
SetDirectory[NotebookDirectory[]];
CreateLibrary[{"addUnit.cc"}, "addUnit", "TargetDirectory" -> NotebookDirectory[]];
where the source file addUnit.cc
is:
//addUnit.cc
#include "WolframLibrary.h"
DLLEXPORT mint WolframLibrary_getVersion(){
return WolframLibraryVersion;}
DLLEXPORT int WolframLibrary_initialize(WolframLibraryData libData){
return 0;}
//global variable part of another package (through extern "C")
mint counter = 0;
//increments global variable 'counter' by one
EXTERN_C DLLEXPORT int addOne(WolframLibraryData libData, mint Argc, MArgument *Args, MArgument Res){
counter++;
return LIBRARY_NO_ERROR;
}
//returns the current value of the global variable 'counter'
EXTERN_C DLLEXPORT int showNumber(WolframLibraryData libData, mint Argc, MArgument *Args, MArgument Res){
MArgument_setInteger(Res, counter);
return LIBRARY_NO_ERROR;
}
This library has a single global variable initialized to counter=0
, which upon calling addOne()
increments it. The function showNumber()
returns the current value. These functions may be called from Mathematica using:
addOneA = LibraryFunctionLoad["addUnit.dylib", "addOne", {}, "Void"];
showNumberA = LibraryFunctionLoad["addUnit.dylib", "showNumber", {}, Integer];
Calling addOneA[]
from Mathematica increments the counter, and showNumberA[]
returns the value.
addOne[]; addOne[];
showNumberA[]
(*2*)
However, I need to initialize a second (and third or even fourth) instance of the library in the same session but with all its global variables confined to these instances.
Unfortunately, loading the functions from these doesn't actually give a separate instance of this library:
addOneB = LibraryFunctionLoad["addUnit.dylib", "addOne", {}, "Void"];
showNumberB = LibraryFunctionLoad["addUnit.dylib", "showNumber", {}, Integer];
for
showNumberB[]
(*2*)
is returning the value of the counter
in the first instance.
Question How do I load multiple instances of the same library via LibraryLink while keeping the global variables of the library local to each instance?