简体   繁体   English

通过Mex文件与C ++对象交互

[英]Interacting with C++ objects through Mex files

I'm a bit stuck on if my current goal is feasible, and if so, how to do this. 如果我目前的目标可行,我会有点坚持,如果可行的话,该如何做到这一点。 I'm hoping to interact with some C++ classes through a Mex file, but I would need the instances of the objects I am accessing to be persistent across calls from different Mex functions. 我希望通过Mex文件与一些C ++类进行交互,但是我需要我访问的对象的实例在来自不同Mex函数的调用中是持久的。 For example, suppose I do the following within an initialization Mex file: 例如,假设我在初始化Mex文件中执行以下操作:

void mexFunction (int nlhs, mxArray *plhs[], int nrhs, const mxArray *prhs[])
{
    size_t nCats = (size_t) *mxGetPr(prhs[0]);

    std::vector<Cat> cats;
    for(size_t i = 0; i <nCats; i++){
         cats[i] = Cat(/* arguments to constructor*/);
    }
}

So I've initialized my Cat objects from my external C++ code. 所以我从外部C ++代码初始化了我的Cat对象。 Now, later down the line, I need to update info about my Cat objects, so in a different Mex file I have 现在,稍后,我需要更新有关我的Cat对象的信息,所以在我有一个不同的Mex文件

void mexFunction (int nlhs, mxArray *plhs[], int nrhs, const mxArray *prhs[])
{

     for(size_t i = 0; i < nCats; i++){
          cats[i].feed(/*parameters to feed method*/);
     }
}

Here are my questions: 这是我的问题:

  1. How would I make this std::vector persist across calls to different Mex files? 如何使这个std :: vector在调用不同的 Mex文件时保持不变? There isn't a way to return non-Matlab types from Mex files (that I'm aware of), and Mathworks says that local variables within Mex functions are generally garbage collected when the function returns, which I do not want. 没有办法从Mex文件中返回非Matlab类型(我知道),并且Mathworks说Mex函数中的局部变量通常在函数返回时被垃圾收集,这是我不想要的。 How can I call the same std::vector with the stored objects I am interested in across different functions? 如何在不同的函数中调用与我感兴趣的存储对象相同的std :: vector? Or even calls to the same function? 甚至调用相同的功能?

  2. Is there a better way to do this with Matlab? 使用Matlab有更好的方法吗? Essentially I'm trying to use Matlab to drive some C++ code, which does the heavy lifting, and then brings it all back to Matlab for analysis. 基本上我正在尝试使用Matlab来驱动一些C ++代码,这些代码完成了繁重的工作,然后将它全部带回Matlab进行分析。 The trouble is that the C++ code is already written, and I need to try to bend Matlab to fit those classes. 问题是C ++代码已经编写完了,我需要尝试修改Matlab以适应这些类。

Not sure if possible between Mex functions but you can make some things persistent between calls to the same mex routine. 不确定Mex函数之间是否可能,但是你可以在调用同一个mex例程之间保持一些持久性。

See documentation for: 请参阅以下文档:

Also see this answer on the Mathworks site: How can I make memory persistent between calls to a MEX-file in MATLAB 另请参阅Mathworks站点上的这个答案: 如何在MATLAB中调用MEX文件之间保持内存持久性

I have not done this myself so can't give more specific help but this might point you in the right direction. 我自己没有这样做,所以不能提供更具体的帮助,但这可能会指出你正确的方向。

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

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