MATLAB MEX接口到具有多个函数的类对象 [英] MATLAB MEX interface to a class object with multiple functions

查看:588
本文介绍了MATLAB MEX接口到具有多个函数的类对象的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我使用MEX界面在MATLAB中运行C ++代码。我想为MATLAB添加几个函数来处理 System 对象:

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()

由于每个MEX dll可以包含一个函数,我需要找到一种方法来存储指向全局 System 对象,它将被调用 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.

MATLAB正确?有没有办法在调用MEX函数时存储全局指针?

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

推荐答案

一个常见的方法是有几个m-提供公共接口,例如sysInit.m,sysRefresh.m等。

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

每个m文件都使用某种句柄调用mex函数,一个字符串(或数字)调用和任何额外的参数。例如,sysRefresh.m可能如下所示:

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')



在您的sysMex mex函数中,您可以将句柄作为原始堆指针,但不是很安全),或者你可以在C / C ++中维护一个从句柄ID到实际对象指针的映射。这个解决方案需要一些额外的工作,但它更安全。这样,有人不能意外地传递任意数字作为句柄,其作为悬挂指针。此外,你可以做更喜欢的事情,例如使用onCleanup函数释放所有的内存和资源,当你卸载mex函数(例如,所以你不必重新启动matlab当你重新编译mex函数)。

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).

如果你喜欢和隐藏在Matlab类后面的句柄,你可以更进一步。如果你有兴趣,阅读文档中的Matlab的OO功能。如果您使用的是最新版本,则可以利用其更干净的句柄对象。

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.

这篇关于MATLAB MEX接口到具有多个函数的类对象的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆