简体   繁体   English

MATLAB MEX接口,具有多个函数的类对象

[英]MATLAB MEX interface to a class object with multiple functions

I am using the MEX interface to run C++ code in MATLAB. 我正在使用MEX接口在MATLAB中运行C ++代码。 I would like to add several functions to MATLAB for handling a System object: 我想在MATLAB中添加几个函数来处理System对象:

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 . 由于每个MEX dll可以包含一个函数,我需要找到一种方法来存储指向全局System对象的指针,该对象将一直存在,直到通过调用sysExit被删除。

How can I do this in MATLAB properly? 我怎样才能在MATLAB中正确执行此操作? Are there any ways to store global pointers across calls to MEX functions? 有没有办法在调用MEX函数时存储全局指针?

One common approach is to have several m-file functions that provide the public interface, eg sysInit.m, sysRefresh.m, etc. 一种常见的方法是提供几个提供公共接口的m文件函数,例如sysInit.m,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. 这些m文件中的每一个都使用某种句柄调用mex函数,标识要调用的函数的字符串(或数字)以及任何额外的args。 For example, sysRefresh.m might look like: 例如,sysRefresh.m可能如下所示:

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. 在sysMex mex函数中,您可以将句柄作为原始堆指针(简单但不是非常安全),或者可以在C / C ++中维护从句柄ID到实际对象指针的映射。 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 (eg so you don't have to restart matlab when you recompile the mex function). 此外,当您卸载mex函数时,您可以使用onCleanup函数来释放所有内存和资源(例如,因此在重新编译mex函数时不必重新启动matlab)。

You can go a bit further if you like and hide the handle behind a Matlab class. 如果你喜欢并隐藏Matlab类后面的句柄,你可以更进一步。 Read up on the OO features for Matlab in the docs if you're interested. 如果您有兴趣,请阅读文档中Matlab的OO功能。 If you're using a recent version, you can take advantage of their much cleaner handle objects. 如果您使用的是最新版本,则可以利用更清晰的处理对象。

Alternatively, you may get away with not using MEX at all. 或者,您可以完全不使用MEX。 In matlab (on Windows) you can load any generic dll with loadlibrary and call any of its functions with callib . 在MATLAB(在Windows上),你可以加载任何通用的dll与loadlibrary ,并调用它的任何功能callib This is probably not portable across operating systems, though. 但是,这可能无法跨操作系统移植。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM