Hi, Ermanno.
Well, I was trying to respond with minimal changes to mosfetâs code so I didnât simplify the code or change it to match my âstyleââŚ
You use static_cast which isnât strictly necessary if you change the passed type from âvoid** opaqueâ to âstateStr** opaqueâ.
Personaly, I also move the instance pointer initialization above the one-time initialization code (so that the pointer can be used inside the one-time initialization code). Then add the instance pointer to the *opaque initialization. My version of your sample looks like this (if I didnât screw it up; long day, working on fumes here):
struct stateStr{
bool clk_state;
stateStr(){
clk_state = false;
}
};
extern "C" __declspec(dllexport) void dac(stateStr **opaque, double t, union uData *data)
{
//inputs and outputs
...
stateStr* instP = *opaque;
// Only once: call constructor
if(!stateStr)
{
instP = *opaque = new stateStr();
}
//Do stuff with instP
...
}
Note: I also always name the per-instance struct âInstDataâ and the pointer pInst. Just my style choice. Consistency has saved a few of my toes. But, you do you.
As for adding Delete(), you donât need the âstructâ keyword in the function signature and, because the instance was allocated with ânewâ, Iâd release with âdeleteâ. (IIRC free() is technically allowed but sort of bad style.)
Do you need to add Destroy()? Technically, Destroy() is called for each instance at the end of each simulation step. If there are multiple steps, each step calls the evaluation function with null **opaque and you allocate new per-instance space. The old instance heap space isnât freed if you donât include Destroy(). All allocated space does eventually get freed when the simulation terminates. But you leak memory until then.
Your example doesnât allocate much per-instance memory so itâs rather inconsequential. On the other hand, you might eventually do something more complicated that allocates more memory, opens files that need to be freed/closed in a destructor, etc. If you donât call delete, destructors defined in the per-instance struct donât get called.
Bottom line: Iâd add Destroy() to ensure that future code revisions donât introduce issues.
So thatâs my two cents worth. Hope it helps.
ârobert