我将Matlab和C代码连接起来,以便能够直接在Matlab中使用某些C函数。我知道这些函数的原型,但是其中的代码可能会更改。为了实现所有接口,我在Matlab中使用loadlibrary和calllib,但我不想使用MEXFiles。
在C代码中,定义了一些结构。但是,定义代码基本组件的代码可能会改变:它包含一些结构和变量,但是可以在其中添加一些其他结构,我希望Matlab能够处理所有这些。
但是,正如Mathworks所说:
不支持嵌套结构或包含指向结构的指针的结构。但是,MATLAB可以访问在外部库中创建的结构数组。
因此,我无法在Matlab中直接存储嵌套结构。例如,主要成分是结构(a)。这个包含另一个结构(b)。并且(b)包含指向函数的指针。如果我使用libstruct直接将(a)存储在变量中,则当我在参数中使用(a)调用C方法时,我们可以看到指针丢失了。最糟糕的是,C代码知道指向结构(b)的指针是什么,但他无法访问指向的函子。但是,通过在Matlab中创建此结构(b)可以实现,但它特定于(b),其他嵌套结构无法做到。
这就是为什么我认为我必须阻止Matlab查看变量的类型。我只是必须给它一个指向该结构的指针,并锁定所有与此指针相关的指针,以便能够使用calllib在C函数的参数中传递此指针。
这就是我的问题:您是否知道我是否可以锁定包含结构(a)以及与之有关的所有内容的一部分内存?而且您认为我可以阻止Matlab查找该指针是什么吗?
实际上,我只想在C函数中创建一个嵌套结构,并在其他C函数中重用它,但是要用Matlab调用这两个C函数(不使用MexFiles)。
谢谢!:)
C代码
结构(一)
typedef struct {
fmi2Real *r;
fmi2Integer *i;
fmi2Boolean *b;
fmi2String *s;
fmi2Boolean *isPositive;
fmi2Real time;
fmi2String instanceName;
fmi2Type type;
fmi2String GUID;
const fmi2CallbackFunctions *functions;
fmi2Boolean loggingOn;
fmi2Boolean logCategories[NUMBER_OF_CATEGORIES];
fmi2ComponentEnvironment componentEnvironment;
ModelState state;
fmi2EventInfo eventInfo;
int isDirtyValues; // !0 is true
} ModelInstance;
可以在该结构(a)中添加其他结构。
结构(b)
typedef struct {
const fmi2CallbackLogger logger;
const fmi2CallbackAllocateMemory allocateMemory;
const fmi2CallbackFreeMemory freeMemory;
const fmi2StepFinished stepFinished;
const fmi2ComponentEnvironment componentEnvironment;
} fmi2CallbackFunctions;
typedef void (*fmi2CallbackLogger) (fmi2ComponentEnvironment, fmi2String, fmi2Status, fmi2String, fmi2String, ...);
typedef void* (*fmi2CallbackAllocateMemory)(size_t, size_t);
typedef void (*fmi2CallbackFreeMemory) (void*);
typedef void (*fmi2StepFinished) (fmi2ComponentEnvironment, fmi2Status);
C功能之一的原型(第一个创建主要组件的原型)
fmi2Component fmi2Instantiate(fmi2String instanceName, fmi2Type fmuType, fmi2String fmuGUID,
fmi2String fmuResourceLocation, const fmi2CallbackFunctions *functions,
fmi2Boolean visible, fmi2Boolean loggingOn);
typedef void* fmi2Component;
Matlab代码
调用函数fmi2Instantiate并创建组件。
fmu.component=calllib(model, 'fmi2Instantiate', libpointer('int8Ptr', fmu.instanceName), fmu.type, libpointer('int8Ptr', fmu.guid), libpointer('int8Ptr', resourceLocation), fmu.callbackFunctions, visible, loggingOn);
该组件将进一步传递给其他C函数。
从您的评论中可以看出,可以有不同的dll,但是导出的函数具有相同的原型,无论如何,我都会将库的管理委派给mex文件。
因此,请让我们考虑构建一个FmiManager.mex
可以在matlab中使用的代码,如下所示:
[ok, msg] = FmiManager('SETUP', libraryName);
[hCallbacks] = FmiManager('CREATE_CALLBACKS', ... params for creating callbacks ...);
[hInstance] = FmiManager('CREATE_INSTANCE', hCallbacks, ... other params ...)
[...] = FmiManager('OTHER_COMMAND', ...);
这很简单,第一个参数是您要对库执行的操作,其他参数特定于要在c代码中调用的函数。
SETUP
是一个额外的命令,用于动态更改与您链接的库。CREATE_CALLBACKS
调用c函数创建回调并返回它们的句柄(例如,只需将c指针强制转换为“结构b”为int)CREATE_INSTANCE
调用c函数以实例化主要组件并返回创建实例的句柄(例如,将“ struct a”再次简单地转换为int),并将回调的句柄作为输入(只需要在内部将其转换回“ struct b” C代码)OTHER_COMMAND
您可以根据需要将过程扩展到其他c功能...这是一些伪代码,显示了如何构建此FmiManager.mex
文件:
[FmiManager.c]
#include <mex.h>
#include <windows.h>
#include "FmiManager.h" // The header for this mex file
#include "fmi.h" // The header for types in your 'fmi' library
// Pointer to correct dll
static HINSTANCE hDll = NULL;
// Pointer to the function that creates the callbacks
typedef fmi2CallbackFunctions* (FMI_CALLCONV createCallBacksPtr *)(...)
static createCallBacksPtr createCallBacks = NULL;
// Pointer to the function that performs instantiation
typedef fmi2Component* (FMI_CALLCONV instanciatePtr *)(...)
static instanciatePtr instanciate = NULL;
// Mex entry point
void mexFunction(int nlhs, mxArray *plhs[], int nrhs, const mxArray *prhs[])
{
// Arguments parsing
if (nrhs < 1) { mexErrMsgTxt("Not enough input arguments."); return; }
if (!mxIsChar(prhs[0])) { mexErrMsgTxt("First parameter must be a string."); return; }
// Command selection
if (commandIs(prhs[0], "SETUP")) { processSetup(nlhs, plhs, nrhs, prhs); }
else if (commandIs(prhs[0], "CREATE_CALLBACKS")) { processCreateCallbacks(nlhs, plhs, nrhs, prhs); }
else if (commandIs(prhs[0], "INSTANCIATE")) { processInstanciate(nlhs, plhs, nrhs, prhs); }
else { mexErrMsgTxt("Unknown command or command not implemented yet."); }
}
// Processing 'SETUP' command
void processSetup(int nlhs, mxArray *plhs[], int nrhs, const mxArray *prhs[])
{
// Free previous library
if (hDll != NULL) { FreeLibrary(hDll); hDll = NULL; }
// Load the new one
char* librayPath = getThisMexPath();
... load library from '*prhs' (i.e. hDll = loadLibrary(fullpath))...
mxFree(librayPath);
// Bind functions pointers
createCallBacks = (createCallBacksPtr)GetProcAddress(hDll, "createCallbacks");
if (createCallBacks == NULL) { mexErrMsgTxt("Failed to map 'createCallBacks'"); return; }
instanciate = (instanciatePtr)GetProcAddress(hDll, "instanciate");
if (instanciate == NULL) { mexErrMsgTxt("Failed to map 'instanciate'"); return; }
}
// Processing 'CREATE_CALLBACKS' command
void processCreateCallbacks(int nlhs, mxArray *plhs[], int nrhs, const mxArray *prhs[])
{
... unpack '*prhs' ...
int hCallbacks = (int)createCallback(...); // Function has been binded during setup
... pack 'hCallbacks' into '*plhs' ...
}
// Processing 'INSTANCIATE' command
void processInstanciate(int nlhs, mxArray *plhs[], int nrhs, const mxArray *prhs[])
{
... unpack '*prhs' ...
int hInstance = (int)instanciate(...); // Function has been binded during setup
... pack 'hInstance' into '*plhs' ...
}
// Check if some command is really some givent one
bool commandIs(const mxArray* mxCommand, const char* command)
{
double result;
mxArray* plhs1[1];
mxArray* prhs1[1];
mxArray* plhs2[1];
mxArray* prhs2[2];
if (mxCommand == NULL) { mexErrMsgTxt("'mxCommand' is null"); return false; }
if (command == NULL) { mexErrMsgTxt("'command' is null"); return false; }
if (!mxIsChar(mxCommand)) { mexErrMsgTxt("'mxCommand' is not a string"); return false; }
// First trim
prhs1[0] = (mxArray*)mxCommand;
mexCallMATLAB(1, plhs1, 1, prhs1, "strtrim");
// Then compare
prhs2[0] = mxCreateString(command);
prhs2[1] = plhs1[0];
mexCallMATLAB(1, plhs2, 2, prhs2, "strcmpi");
// Return comparison result
result = mxGetScalar(plhs2[0]);
return (result != 0.0);
}
// Obtain the path of current mex file
// CAREFUL: Use mxFree on return pointer !!
char* getThisMexPath()
{
mxArray *rhs[1], *lhs[1];
char *path, *name;
size_t lenpath, lenname, n;
rhs[0] = mxCreateString("fullpath");
mexCallMATLAB(1, lhs, 1, rhs, "mfilename");
mxDestroyArray(rhs[0]);
path = mxArrayToString(lhs[0]);
mxDestroyArray(lhs[0]);
mexCallMATLAB(1, lhs, 0, rhs, "mfilename");
name = mxArrayToString(lhs[0]);
mxDestroyArray(lhs[0]);
lenpath = strlen(path);
lenname = strlen(name);
n = lenpath - lenname;
path[n] = '\0';
mxFree(name);
return path; // Don't forget mxFree !!!
}
我希望您会喜欢这种替代解决方案。它的主要优点是您不必费心确保在matlab中创建的结构将适合c端代码。一切都委托给.mex文件(即,在c中),并作为句柄传递给matlab。
本文收集自互联网,转载请注明来源。
如有侵权,请联系[email protected] 删除。
我来说两句