MATLAB MEX interface to a class object with multiple functions

﹥>﹥吖頭↗ 提交于 2019-12-10 12:55:48

问题


I am using the MEX interface to run C++ code in MATLAB. I would like to add several functions to MATLAB for handling a System object:

sysInit()
sysRefresh()
sysSetAttribute(name, value)
String = sysGetAttribute(value)
sysExit()

Since each MEX dll can contain one function, I need to find a way to store the pointer to the global System object which will exist until deleted by a call to sysExit.

How can I do this in MATLAB properly? Are there any ways to store global pointers across calls to MEX functions?


回答1:


One common approach is to have several m-file functions that provide the public interface, e.g. sysInit.m, sysRefresh.m, etc.

Each of these m-files calls the mex function with some kind of handle, a string (or number) identifying the function to call, and any extra args. For example, sysRefresh.m might look like:

function sysRefresh(handle)
return sysMex(handle, 'refresh')

In your sysMex mex function, you can either have the handle be a raw heap pointer (easy, but not very safe), or you can maintain a mapping in C/C++ from the handle ID to the actual object pointers. This solution requires a little extra work, but it's much safer. This way someone can't accidentally pass an arbitrary number as a handle, which acts as a dangling pointer. Also, you can do fancier things like use an onCleanup function to release all memory and resources when you unload the mex function (e.g. so you don't have to restart matlab when you recompile the mex function).

You can go a bit further if you like and hide the handle behind a Matlab class. Read up on the OO features for Matlab in the docs if you're interested. If you're using a recent version, you can take advantage of their much cleaner handle objects.




回答2:


Alternatively, you may get away with not using MEX at all. In matlab (on Windows) you can load any generic dll with loadlibrary and call any of its functions with callib. This is probably not portable across operating systems, though.



来源:https://stackoverflow.com/questions/1182183/matlab-mex-interface-to-a-class-object-with-multiple-functions

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!