MATLAB函数手柄和C 功能指针

Matlab function handles and C++ function pointers

本文关键字:功能 指针 函数 MATLAB      更新时间:2023-10-16

是否有可能使MATLAB函数手柄与C 功能指针兼容?我正在尝试从MATLAB调用C 功能,该功能接收C 功能指针。例如:

c :

void Cfunction( C++functionPointer);

matlab:

function out Mfunction(functionHandle)
     out= Cfunction(functionHandle)

不幸的是,我无法发布代码,因为它是机密的。因此,我希望我的MATLAB程序使用Calllib()调用C 功能。C 函数的参数之一是功能指针。在MATLAB中,我尝试使用MATLAB函数句柄作为Callib中的参数,但这无效。因此,我很难从MATLAB调用C 函数。

MATLAB说C 编译器将不接受其指针参数的MATLAB函数句柄类型。

谢谢

好吧,因此,据我了解,您有一个带有函数的c 库(让我称其为 functionFromMyCppLibrary),您可以运行。该功能需要的参数之一是功能指针。

我假设此功能指针必须是C 函数。如果functionFromMyCppLibrary需要调用任意MATLAB功能,则我的答案不适用。但是,在Mathworks交换中有一个Q& a可能会发现有用:如何将功能句柄传递给MATLAB 7.8(R2009A)中的C MEX函数?您可能需要在下面修改CppFunction,以使MATLAB调用feval。如果您可以在CppFunction()中进行硬码MATLAB函数名称。

,它实际上会变得更容易

callTheCppThing.cpp

#include "mex.h"
#include "myCppLibrary.h"
void CppFunction()
{
    // The function your C++ library requires as a function pointer
    // You could use mexCallMATLAB here to call a Matlab function,
    // but it will get trickier if you can't hard-code the name of
    // the Matlab function here
}
void mexFunction(int nlhs, mxArray *plhs[], int nrhs, mxArray *prhs[])
{
    // Process however you need the arguments
    functionFromMyCppLibrary(CppFunction);
    // Create the output variables and return whatever Matlab needs
}

您可以用

编译
mex callTheCppThing.cpp

(添加到此命令行链接此C 与您的库所需的任何内容。)

,您从Matlab打电话给

callTheCppThing

这消除了MATLAB的需要,将任何类型的手柄传递给您的C 库。(如果您没有可能在C 中编写不同的包装器,请检查链接的Q& a来自Mathworks。这很棘手,但可能。)