如何将一个C++代码工程转换为matlab的mex文件直接调用呢

1)首先我们要写一个接口函数mexFunction(),这个接口函数就是类似C++的main函数,它是入口函数,传递参数给我们的C++函数。

#include "mex.h" //mx函数,mex函数用到的头文件

#include "exp.h"//调用函数用到的头文件

void mexFunction(int nlhs,mxArray *plhs[],int nrhs,const mxArray *prhs[])
{
    char *buff;
    int M,N,state,len;
    //if (nlhs>1)
        //mexErrMsgTxt("Too many output argument!");
    if (nrhs!=1)
        {
            mexErrMsgTxt("Must have two input argument!");
        }
    //prhs[0] = mxCreateString(a);
    M = mxGetM(prhs[0]);//获得输入参数的行
    N = mxGetN(prhs[0]);//获得输入参数的列
    len = M*N+1;
    buff = (char*)mxCalloc(len,sizeof(char));//申请内存空间,mxCalloc类是C语言的Calloc
    state = mxGetString(prhs[0],buff,len);//把prhs[0]由mxArray类型字符转换为char类型
    if (state!=0)
        mexWarnMsgTxt("Not enough space. String is truncated.");
    print(buff);//调用写好的C++函数,我们传递的是字符指针
}

2)接下来写C++函数了,记住C++函数要单独一个CPP文件,这样有利与之后的mex文件编译。

//print.cpp
#include "exp.h"
#include "mex.h"
void print (char *a)
{
   
    mexPrintf ("%s jiangfeng\n",a);
    Array();//函数的嵌套调用
}
//Array.cpp
#include "exp.h"
void Array()
{
    int i,a[10]={1,2,3,4,5,6,7,9,8,0};
    for (i=0;i<10;i++)
    {
        mexPrintf ("%d ",a[i]);
    }
    mexPrintf ("\n");
    test();//函数嵌套调用
}
//test.cpp
#include "exp.h"
void test()
{
    mexPrintf ("very good !\n");
}
//exp.h
#ifndef EXP_H
#define EXP_H
#include "mex.h"
void print (char *a);

void Array();
void test();

#endif
3)编译C++代码生成mex文件
mex print.cpp Array.cpp test.cpp mexFunction.cpp
之后产生print.mexa64文件,这个文件可以在matlab下直接运行,如:
>>print(‘hello world’)
hello world jiangfeng
1 2 3 4 5 6 7 8 9 0
very good !
>>
如果在mex print.cpp Array.cpp test.cpp mexFunction.cpp 过程中出现下面错误,如:


Mex file entry point is missing.  Please check the (case-sensitive)
spelling of mexFunction (for C MEX-files), or the (case-insensitive)
spelling of MEXFUNCTION (for FORTRAN MEX-files).



这种错误说明mexFunction()的参数格式不正确,应该严格按照格式书写
void mexFunction(int nlhs,mxArray *plhs[],int nrhs,const mxArray *prhs[])


well done


  • 0
    点赞
  • 7
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

feng_blog6688

只需一个赞,谢谢你的鼓励

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值