乔延柯的博客分享 http://blog.sciencenet.cn/u/bewinner 在通往梦想的路上

博文

matlab和C++程序接口编程

已有 5744 次阅读 2015-3-7 20:01 |个人分类:工作求职|系统分类:科研笔记| MATLAB, medium, style, color, 程序

1.在C++程序中编译必须定义接口函数为:
void mexFunction( int nlhs, mxArray *plhs[],
                 int nrhs, const mxArray *prhs[] )
nlhs输出变量个数
plhs输出变量地址数组
nrhs输入变量个数
prhs输入变量地址数组

2.mxGetScalar(prhs[0]);读取输入变量数组第一个的数值
mxGetPr(plhs[0]);读取输入变量数组第一个的地址

3.几个概念
  • mexFunction即为主函数,在C程序中不能再有main函数

  • 输出参数,必须要在mex函数中先申请内存,如通过 mxCreateDoubleMatrix,申请double类型空间

  • 如果输出参数不为double类型,就需要申请非double类型的空间,用函数mxCreateNumericMatrix,可以指定数据空间。

4.关于函数mxCreateNumericMatrix,其调用函数为mxCreateNumericMatrix(1,1,mxINT32_CLASS,0),第一二个参数代表是1×1的矩阵,第三个参数代表申请int32类型的空间,第四个参数为0表示为不包含虚部的实数,为1表示包含虚部。

为保证清晰理解,特贴一个实例。仔细研磨就可融汇贯通。

#include "mex.h"
 
/*
* timestwoalt.c - example found in API guide
*
* use mxGetScalar to return the values of scalars instead of pointers
* to copies of scalar variables.
*
* This is a MEX-file for MATLAB.
* Copyright 1984-2011 The MathWorks, Inc.
*/
 
/* $Revision: 1.6.6.1 $ */
 
void timestwo_alt(unsigned short *y, double x)
{
 *y = 2.0*x;
}
 
void mexFunction( int nlhs, mxArray *plhs[],
                 int nrhs, const mxArray *prhs[] )
{
  unsigned short *y;
  double  x;
 
   /* Check arguments */
 
  if (nrhs != 1) {
   mexErrMsgIdAndTxt( "MATLAB:timestwoalt:invalidNumInputs" ,
           "One input argument required." );
 } else if (nlhs > 1) {
   mexErrMsgIdAndTxt( "MATLAB:timestwoalt:maxlhs" ,
           "Too many output arguments." );
 } else if (!mxIsNumeric(prhs[0])) {
   mexErrMsgIdAndTxt( "MATLAB:timestwoalt:invalidInputType" ,
           "Argument must be numeric." );
 } else if (mxGetNumberOfElements(prhs[0]) != 1 || mxIsComplex(prhs[0])) {
   mexErrMsgIdAndTxt( "MATLAB:timestwoalt:inputNotRealScalar" ,
           "Argument must be non-complex scalar." );
 }
  /* create a 1-by-1 matrix for the return argument */
 plhs[0] = mxCreateNumericMatrix(1,1,mxINT32_CLASS,0);
 
  /* get the scalar value of the input x */
  /* note: mxGetScalar returns a value, not a pointer */
 x = mxGetScalar(prhs[0]);
 
  /* assign a pointer to the output */
 y = (unsigned short *)mxGetPr(plhs[0]);
 
  /* call the timestwo_alt subroutine */
 timestwo_alt(y,x);
}
 




https://wap.sciencenet.cn/blog-496389-872720.html

上一篇:关于《三体》
下一篇:白日幻想——写给读书会
收藏 IP: 58.38.9.*| 热度|

0

该博文允许注册用户评论 请点击登录 评论 (0 个评论)

数据加载中...
扫一扫,分享此博文

Archiver|手机版|科学网 ( 京ICP备07017567号-12 )

GMT+8, 2024-4-29 09:05

Powered by ScienceNet.cn

Copyright © 2007- 中国科学报社

返回顶部