MATLAB array of libpointer

MATLAB array of libpointer

本文关键字:libpointer of array MATLAB      更新时间:2023-10-16

我目前正在开发一个c++库的包装器,因此它可以在MATLAB中使用。我希望我的c++对象在MATLAB中,这样用户就可以用它们做一些事情。实际上,我正在将这些c++对象转换为void *,因为MATLAB只支持C头。这些C函数是这样的:

__declspec(dllexport) void *getPtr (int someArgument);

在MATLAB中,我这样调用函数:

ptr = calllib('LibName', 'getPtr', 42);

在MATLAB中,ptr现在是<1x1 lib.pointer>。除了将它传递给另一个C函数之外,我不能对它做任何事情,就像下面这样:

__declspec(dllexport) int doSomethingWithPtr (void *ptr);

所以我在MATLAB中调用result = calllib('LibName', 'doSomethingWithPtr', ptr);,它工作得很好,并以指针作为参数执行此函数。(我已经调试了C代码,指针与getPtr返回的指针相同。

我的C函数需要不止一个指针才能像c++库那样工作。我已经将MATLAB矩阵中的数字数据传递给C,它与C类型mxArray完美配合(参见:http://www.mathworks.de/de/help/matlab/apiref/mxarray.html)。为了将多个指针交给C,我构造了一个MATLAB lib.pointer数组,如下所示:

A = [];
for i = 1:10
    ptr = calllib('LibName', 'getPtr', i);
    A = [A, ptr];    
end

我在MATLAB中调用另一个C函数(__declspec(dllexport) int doSomethingWithPtrArray (mxArray *ptrarr);):

ptr = calllib('LibName', 'doSomethingWithPtrArray', A);

在C函数中,我获得了mxGetN(ptrarr)mxGetM(ptrarr)的正确数组尺寸。我还可以检索数据指针:

void *mexPtr = mxGetData(ptrarr);

问题是mexPtr和以下指针指向内存中的位置,我甚至没有分配或知道之前。也许MATLAB在使用void *调用函数时做了一些智能包装,当我通过数组时不这样做。(我认为我正在获得MATLAB lib.pointer包装器对象的地址??)

有没有人有线索(或解决方案)我如何得到正确的指针从mxArray,所以我可以评估多个指针一次?

由于我没有找到"漂亮"的解决方案,我在c++中构造了一个助手方法,它可以让我构建自己的向量:

void *buildClassifierVectorBase(void *vector, void *classifier)
{
    typedef IClassifierManager<input_dtype, feature_dtype, annotation_dtype> class_man_t;
    std::vector<std::shared_ptr<class_man_t>> *classMgrs;
    if (vector == nullptr)
    {
        classMgrs = new std::vector<std::shared_ptr<class_man_t>>();            
    } 
    else
    {
        classMgrs = static_cast<std::vector<std::shared_ptr<class_man_t>> *>(vector);
    }
    class_man_t *cls = static_cast<class_man_t *>(classifier);
    classMgrs->push_back(std::shared_ptr<class_man_t>(cls));        
    return static_cast<void *>(classMgrs);  
}

我可以在MATLAB中使用这种方法来构建这样的指针向量:

ptr1 = calllib('LibName', 'getPtr', 42);
ptr2 = calllib('LibName', 'getPtr', 43);
ptr3 = calllib('LibName', 'getPtr', 44);
vector = calllib('LibName', 'buildClassifierVectorBase', libpointer, ptr1);
vector = calllib('LibName', 'buildClassifierVectorBase', vector, ptr2);
vector = calllib('LibName', 'buildClassifierVectorBase', vector, ptr3);

现在我可以调用方法doSomethingWithPtrArray:

ptr = calllib('LibName', 'doSomethingWithPtrArray', vector);