MATLAB打包

本次使用的MATLAB版本为R2022b

  1. 首先要将MATLAB脚本封装为函数

  2. 在MATLAB APP中下载MATLAB CompilerMATLAB Compiler SDK

  3. 在MATLAB命令行中运行deploytool,选择Library Compiler

  4. TYPE中选择C++ Shared Library,在EXPORTED FUNCTIONS中点+号添加要封装的m文件

  5. 点击Package生成,此时目录下应该生成了MainBallistic_Guidance文件夹,包含封装好的so文件和h文件

C++ 调用

编写一个测试文件,根据h文件中的API调用封装好的函数。本次实验使用的test.cpp代码如下:

#include "libMainBallistic_Guidance.h"
#include <iostream>

int main(){
    // Initialize the library
    if (!libMainBallistic_GuidanceInitialize()) {
        std::cerr << "Could not initialize the library!" << std::endl;
        return -1;
    }

    // Call the MATLAB function through the library
    int nlhs = 1; 
    mxArray *plhs[1];
    int nrhs = 0;
    mxArray *prhs[0];
    bool success = mlxMainBallistic_Guidance(nlhs, plhs, nrhs, prhs);

    if (!success) {
        std::cerr << "Error calling MATLAB function!" << std::endl;
        return -1;
    }

    // Get output from MATLAB function
    double *output = mxGetPr(plhs[0]);

    // Print output
    std::cout << "Output from MATLAB function: " << output[0] << std::endl;

    // Cleanup
    mxDestroyArray(plhs[0]);
    libMainBallistic_GuidanceTerminate();

    return 0;

}

MATLAB中会将变量保存至一个mat文件中,再用一个read.cpp文件来读取数据:

#include <matio.h>

int main()
{
    // 打开 MATLAB .mat 文件
    mat_t *matfp;
    matfp = Mat_Open("data.mat", MAT_ACC_RDONLY);
    if (!matfp) {
        printf("Error opening file.\n");
        return 1;
    }

    // 从文件中读取指定的变量
    matvar_t *matvar;
    matvar = Mat_VarRead(matfp, "arrayXm");
    if (!matvar) {
        printf("Error reading variable.\n");
        return 1;
    }

    // 处理读取的数据
    double *data = (double*)matvar->data;
    int num_elems = matvar->dims[0]*matvar->dims[1];
    for (int i = 0; i < num_elems; i++) {
        printf("%f ", data[i]);
    }
    printf("\n");

    // 释放资源
    Mat_VarFree(matvar);
    Mat_Close(matfp);

    return 0;
}

C++ 编译

  1. 下载对应版本的MATLAB runtime,解压后安装,后面需要用到安装路径

  2. 先添加库文件的路径到环境变量,要包含MATLAB runtime的路径和封装库所在的路径

    export LD_LIBRARY_PATH=/home/why/workspace/mtoc++/libMainBallistic_Guidance/for_redistribution_files_only:/home/why/program/MATLAB/R2022b/runtime/glnxa64:/home/why/program/MATLAB/R2022b/bin/glnxa64:$LD_LIBRARY_PATH
    
  3. 编译test.cpp

    g++ -o test test.cpp -I/home/why/program/MATLAB/R2022b/extern/include \
    -L/home/why/workspace/mtoc++/libMainBallistic_Guidance/for_redistribution_files_only \
    -L/home/why/program/MATLAB/runtime/R2022b/runtime/glnxa64 \
    -L/home/why/program/MATLAB/runtime/R2022b/bin/glnxa64 \
    -L/home/why/program/MATLAB/runtime/R2022b/sys/os/glnxa64 \
    -lMainBallistic_Guidance -lmwmclmcrrt \
    -lmex -lmat -lmwfl 
    
  4. 运行test

    ./test
    
  5. 发现结果可以正常输出,也会在目录下生成data.mat

  6. 编译read.cpp,需要matio

    sudo apt install libmatio-dev
    

    然后编译

    g++ -Wall -I/path/to/matio/include read.cpp -L/path/to/matio/lib -lmatio -o read
    
  7. 运行read,可以输出结果

    ./read