Azzera filtri
Azzera filtri

How to work with persistent class objects in C++ MEX s-function?

3 visualizzazioni (ultimi 30 giorni)
Hi,
I'm trying to develop a level-2 s-function using C++. The s-function uses a class similar to the following:
class TestClass
{
private:
int m1;
int m2;
char m3;
string m4;
public:
TestClass(int pm1, int pm2, char pm3)
{
m1 = pm1;
m2 = pm2;
m3 = pm3;
m4 = "Dodo";
}
};
An object of TestClass is created & initialised in mdlStart(). The object needs to be persistent so that it can be used in mdlOuptuts() and mdlTerminate(). This has been done using DWork vector as follows:
mdlInitializeSizes()
...
ssSetDWorkName(S, 5, "Test2");
ssSetDWorkUsageType(S, 5, SS_DWORK_USED_AS_DWORK);
ssSetDWorkDataType(S, 5, SS_POINTER);
ssSetDWorkWidth(S, 5, 1);
...
mdlStart()
...
TestClass **Test2_DWork = (TestClass **)ssGetDWork(S, 5);
TestClass t1(13, 25, 'K');
Test2_DWork[0] = &t1;
...
The member functions/variables would then be used in mdlOutputs() as follows:
mdlOutputs()
...
int tmp_m1 = (*Test2_DWork[0]).m1;
...
However, mdlOutputs() does not recognise the object retrieved from DWork vector as an instance of TestClass. I tried debugging it using visual studio. The base address object t1 in mdlStart() was noted. The contents of the memory at that base address matched the values when object t1 was created. But once, the execution leaves mdlStart() and enters mdlOutputs(), the contents of the memory at the aforementioned base address change.
If object t1 is declared as static during creation in mdlStart() it works as expected. However, the s-function would become part of a library so cannot use static variables. How can I ensure that the object is persistent without making it static? Is it possible to pass the object by-value between s-function methods?
Any pointers would be much appreciated.
Many thanks, sunny

Risposte (0)

Community Treasure Hunt

Find the treasures in MATLAB Central and discover how the community can help you!

Start Hunting!

Translated by