Search All of the Math Forum:
Views expressed in these public forums are not endorsed by
Drexel University or The Math Forum.
|
|
|
|
Re: Making C++ objects persistent between mex calls, and robust.
Posted:
Jan 21, 2013 6:05 PM
|
|
Oliver, you have made an error in your set function. The last line of the function should be changed as follows:
void set(double *input) { this->data = (double*) mxCalloc(1, sizeof(double)); mexMakeMemoryPersistent(this->data); *this->data = *input; }
Do you see why?
However, by allocating memory and not freeing it in a destructor, you leave your code open to memory leaks. In fact, before I fixed the bug above, your code *was* leaking memory. I would rewrite the dummy class to be much simpler and avoid any leaks, as follows:
class dummy { public: void set(double input) { data = input; } double get() { return data; } private: double data; };
The "set" part of mexFunction is then: if (!strcmp("set", cmd)) { dummy_instance->set(mxGetScalar(prhs[2])); return; }
The "get" part of mexFunction is: if (!strcmp("get", cmd)) { plhs[0] = mxCreateDoubleScalar(dummy_instance->get()); return; }
The "delete" part of mexFunction is changed to: if (!strcmp("delete", cmd)) { // Destroy the C++ object destroyObject<dummy>(prhs[1]); return; }
Much simpler! Hope that helps. Oliver
|
|
|
|