Matlab与C/C++联合编程之Matlab以MEX方式调用C/C++代码(三)

2024-01-15 15:32

本文主要是介绍Matlab与C/C++联合编程之Matlab以MEX方式调用C/C++代码(三),希望对大家解决编程问题提供一定的参考价值,需要的开发者们随着小编来一起学习吧!

最近写了个Matlab程序,好慢呐……所以开始学习Matlab与C/C++混合编程。下面写了个测试代码,显示一个Double类型矩阵中的元素。

源代码

#include "mex.h"

void displaySubscript( const mxArray *pArray, mwSize index );

// 入口函数
void mexFunction( int nlhs, mxArray *plhs[], int nrhs, const mxArray *prhs[] ) {
    
    // 源文件名后缀为.c时,所有变量声明必须一次性完成,且放在最前面, 否则mex编译错误
    // 源文件名后缀为.cpp时,没有上面的问题,...- -||
    double *pData;
    mwSize i;
    
    // 输入参数必须为一个,且为double类型
    if ( nrhs != 1 || mxDOUBLE_CLASS != mxGetClassID(prhs[0]) ) {
        mexErrMsgTxt( "输入参数不合法……" );
    }
    
    // 获取数据指针
    pData = mxGetPr(prhs[0]);
    
    // 遍历所有元素并打印到屏幕
    for ( i = 0; i != mxGetNumberOfElements(prhs[0]); i++ ) {
        displaySubscript( prhs[0], i );
        mexPrintf( " = %g/n", pData[i] );
    }
}

void displaySubscript( const mxArray *pArray, mwSize index ) {
    
    // 源文件名后缀为.c时,所有变量声明必须一次性完成,且放在最前面, 否则mex编译错误
    // 源文件名后缀为.cpp时,没有上面的问题,...- -||,代码好龊...
    mwSize i, j;
    mwSize numOfDim;
    mwSize *subScript;
    mwSize subIndex;
    mwSize total;
    
    const mwSize *Dims;
    const char *className;
    
    // 获取维度个数
    numOfDim = mxGetNumberOfDimensions(pArray);
    // 获取维度数组
    Dims = mxGetDimensions(pArray);
    // 获取类型名称
    className = mxGetClassName(pArray);
    // 分配下标数组内存
    subScript = (mwSize *)mxCalloc( numOfDim, sizeof( mwSize ) );
    
    // 根据当前的索引号生成下标
    subIndex = index;
    for ( i = numOfDim - 1; ; i-- ) {
        total = 1;
        
        for ( j = 0; j < i; j++ ) {
            total *= Dims[j];
        }
        
        subScript[i] = subIndex / total;
        subIndex = subIndex % total;
        
        if ( 0 == i ) {
            break;
        }
    }
    
    // 打印出所有下标
    mexPrintf( "(" );
    for ( i = 0; i < numOfDim - 1; i++ ) {
        mexPrintf( "%d,", subScript[i] + 1 );
    }
    mexPrintf( "%d)", subScript[numOfDim-1] + 1 );
    
    // 释放下标数组内存
    mxFree( subScript );
}

在Matlab使用mex命令编译源文件时,要注意这样一个现象:源文件名后缀为.c时,所有变量声明必须一次性完成,且放在最前面, 否则mex编译错误;而源文件名后缀为.cpp时,就没有上面的问题,...- -||。

实验结果

混合编程API一览

MX Matrix Library

mwIndex (C and Fortran)

Type for index values

mwPointer (Fortran)

Pointer type for platform

mwSignedIndex (C and Fortran)

Signed integer type for size values

mwSize (C and Fortran)

Type for size values

mxAddField (C and Fortran)

Field to structure array

mxArray (C and Fortran)

Type for MATLAB array

mxArrayToString (C)

Convert array to string

mxAssert (C)

Check assertion value for debugging purposes

mxAssertS (C)

Check assertion value without printing assertion text

mxCalcSingleSubscript (C and Fortran)

Offset from first element to desired element

mxCalloc (C and Fortran)

Allocate dynamic memory for array using MATLAB memory manager

mxChar (C)

Type for string array

mxClassID (C)

Enumerated value identifying class of array

mxClassIDFromClassName (Fortran)

Identifier corresponding to class

mxComplexity (C)

Flag specifying whether array has imaginary components

mxCopyCharacterToPtr (Fortran)

CHARACTER values from Fortran array to pointer array

mxCopyComplex16ToPtr (Fortran)

COMPLEX*16 values from Fortran array to pointer array

mxCopyComplex8ToPtr (Fortran)

COMPLEX*8 values from Fortran array to pointer array

mxCopyInteger1ToPtr (Fortran)

INTEGER*1 values from Fortran array to pointer array

mxCopyInteger2ToPtr (Fortran)

INTEGER*2 values from Fortran array to pointer array

mxCopyInteger4ToPtr (Fortran)

INTEGER*4 values from Fortran array to pointer array

mxCopyPtrToCharacter (Fortran)

CHARACTER values from pointer array to Fortran array

mxCopyPtrToComplex16 (Fortran)

COMPLEX*16 values from pointer array to Fortran array

mxCopyPtrToComplex8 (Fortran)

COMPLEX*8 values from pointer array to Fortran array

mxCopyPtrToInteger1 (Fortran)

INTEGER*1 values from pointer array to Fortran array

mxCopyPtrToInteger2 (Fortran)

INTEGER*2 values from pointer array to Fortran array

mxCopyPtrToInteger4 (Fortran)

INTEGER*4 values from pointer array to Fortran array

mxCopyPtrToPtrArray (Fortran)

Pointer values from pointer array to Fortran array

mxCopyPtrToReal4 (Fortran)

REAL*4 values from pointer array to Fortran array

mxCopyPtrToReal8 (Fortran)

REAL*8 values from pointer array to Fortran array

mxCopyReal4ToPtr (Fortran)

REAL*4 values from Fortran array to pointer array

mxCopyReal8ToPtr (Fortran)

REAL*8 values from Fortran array to pointer array

mxCreateCellArray (C and Fortran)

Unpopulated N-D cell array

mxCreateCellMatrix (C and Fortran)

Unpopulated 2-D cell array

mxCreateCharArray (C and Fortran)

Unpopulated N-D string array

mxCreateCharMatrixFromStrings (C and Fortran)

Create populated 2-D string array

mxCreateDoubleMatrix (C and Fortran)

2-D, double-precision, floating-point array initialized to 0

mxCreateDoubleScalar (C and Fortran)

Scalar, double-precision array initialized to specified value

mxCreateLogicalArray (C)

N-D logical array initialized to false

mxCreateLogicalMatrix (C)

2-D, logical array initialized to false

mxCreateLogicalScalar (C)

Scalar, logical array

mxCreateNumericArray (C and Fortran)

Unpopulated N-D numeric array

mxCreateNumericMatrix (C and Fortran)

Numeric matrix initialized to 0

mxCreateSparse (C and Fortran)

2-D unpopulated sparse array

mxCreateSparseLogicalMatrix (C)

Unpopulated 2-D, sparse, logical array

mxCreateString (C and Fortran)

Create 1-by-N array initialized to specified string

mxCreateStructArray (C and Fortran)

Unpopulated N-D structure array

mxCreateStructMatrix (C and Fortran)

Unpopulated 2-D structure array

mxDestroyArray (C and Fortran)

Free dynamic memory allocated by MXCREATE* functions

mxDuplicateArray (C and Fortran)

Make deep copy of array

mxFree (C and Fortran)

Free dynamic memory allocated by MXCALLOC, MXMALLOC, or MXREALLOC functions

mxGetCell (C and Fortran)

Contents of array cell

mxGetChars (C)

Pointer to character array data

mxGetClassID (C and Fortran)

Class of array

mxGetClassName (C and Fortran)

Class of array as string

mxGetData (C and Fortran)

Pointer to real data

mxGetDimensions (C and Fortran)

Pointer to dimensions array

mxGetElementSize (C and Fortran)

Number of bytes required to store each data element

mxGetEps (C and Fortran)

Value of EPS

mxGetField (C and Fortran)

Field value, given field name and index, into structure array

mxGetFieldByNumber (C and Fortran)

Field value, given field number and index, into structure array

mxGetFieldNameByNumber (C and Fortran)

Field name, given field number, in structure array

mxGetFieldNumber (C and Fortran)

Field number, given field name, in structure array

mxGetImagData (C and Fortran)

Pointer to imaginary data of array

mxGetInf (C and Fortran)

Value of infinity

mxGetIr (C and Fortran)

Sparse matrix IR array

mxGetJc (C and Fortran)

Sparse matrix JC array

mxGetLogicals (C)

Pointer to logical array data

mxGetM (C and Fortran)

Number of rows in array

mxGetN (C and Fortran)

Number of columns in array

mxGetNaN (C and Fortran)

Value of NaN (Not-a-Number)

mxGetNumberOfDimensions (C and Fortran)

Number of dimensions in array

mxGetNumberOfElements (C and Fortran)

Number of elements in array

mxGetNumberOfFields (C and Fortran)

Number of fields in structure array

mxGetNzmax (C and Fortran)

Number of elements in IR, PR, and PI arrays

mxGetPi (C and Fortran)

Imaginary data elements in array of type DOUBLE

mxGetPr (C and Fortran)

Real data elements in array of type DOUBLE

mxGetProperty (C and Fortran)

Value of public property of MATLAB object

mxGetScalar (C and Fortran)

Real component of first data element in array

mxGetString (C and Fortran)

String array to C-style string

mxIsCell (C and Fortran)

Determine whether input is cell array

mxIsChar (C and Fortran)

Determine whether input is string array

mxIsClass (C and Fortran)

Determine whether array is member of specified class

mxIsComplex (C and Fortran)

Determine whether data is complex

mxIsDouble (C and Fortran)

Determine whether mxArray represents data as double-precision, floating-point numbers

mxIsEmpty (C and Fortran)

Determine whether array is empty

mxIsFinite (C and Fortran)

Determine whether input is finite

mxIsFromGlobalWS (C and Fortran)

Determine whether array was copied from MATLAB global workspace

mxIsInf (C and Fortran)

Determine whether input is infinite

mxIsInt16 (C and Fortran)

Determine whether array represents data as signed 16-bit integers

mxIsInt32 (C and Fortran)

Determine whether array represents data as signed 32-bit integers

mxIsInt64 (C and Fortran)

Determine whether array represents data as signed 64-bit integers

mxIsInt8 (C and Fortran)

Determine whether array represents data as signed 8-bit integers

mxIsLogical (C and Fortran)

Determine whether array is of type mxLogical

mxIsLogicalScalar (C)

Determine whether scalar array is of type mxLogical

mxIsLogicalScalarTrue (C)

Determine whether scalar array of type mxLogical is true

mxIsNaN (C and Fortran)

Determine whether input is NaN (Not-a-Number)

mxIsNumeric (C and Fortran)

Determine whether array is numeric

mxIsSingle (C and Fortran)

Determine whether array represents data as single-precision, floating-point numbers

mxIsSparse (C and Fortran)

Determine whether input is sparse array

mxIsStruct (C and Fortran)

Determine whether input is structure array

mxIsUint16 (C and Fortran)

Determine whether array represents data as unsigned 16-bit integers

mxIsUint32 (C and Fortran)

Determine whether array represents data as unsigned 32-bit integers

mxIsUint64 (C and Fortran)

Determine whether array represents data as unsigned 64-bit integers

mxIsUint8 (C and Fortran)

Determine whether array represents data as unsigned 8-bit integers

mxLogical (C)

Type for logical array

mxMalloc (C and Fortran)

Allocate dynamic memory using MATLAB memory manager

mxRealloc (C and Fortran)

Reallocate dynamic memory using MATLAB memory manager

mxRemoveField (C and Fortran)

Remove field from structure array

mxSetCell (C and Fortran)

Value of one cell of array

mxSetClassName (C)

Convert structure array to MATLAB object array

mxSetData (C and Fortran)

Set pointer to data

mxSetDimensions (C and Fortran)

Modify number of dimensions and size of each dimension

mxSetField (C and Fortran)

Set structure array field, given structure field name and array index

mxSetFieldByNumber (C and Fortran)

Set structure array field, given field number and index

mxSetImagData (C and Fortran)

Imaginary data pointer for array

mxSetIr (C and Fortran)

IR array of sparse array

mxSetJc (C and Fortran)

JC array of sparse array

mxSetM (C and Fortran)

Number of rows in array

mxSetN (C and Fortran)

Set number of columns in array

mxSetNzmax (C and Fortran)

Set storage space for nonzero elements

mxSetPi (C and Fortran)

Set new imaginary data for array

mxSetPr (C and Fortran)

Set new real data for array

mxSetProperty (C and Fortran)

Set value of public property of MATLAB object

MEX Library

 

mexAtExit (C and Fortran)

Register function to call when MEX-function cleared or MATLAB software terminates

mexCallMATLAB (C and Fortran)

Call MATLAB function, user-defined function, or MEX-file

mexCallMATLABWithTrap (C and Fortran)

Call MATLAB function, user-defined function, or MEX-file and capture error information

mexErrMsgIdAndTxt (C and Fortran)

Display error message with identifier and return to MATLAB prompt

mexErrMsgTxt (C and Fortran)

Display error message and return to MATLAB prompt

mexEvalString (C and Fortran)

Execute MATLAB command in caller workspace

mexEvalStringWithTrap (C and Fortran)

Execute MATLAB command in caller workspace and capture error information

mexFunction (C and Fortran)

Entry point to C/C++ or Fortran MEX-file

mexFunctionName (C and Fortran)

Name of current MEX-function

mexGet (C)

Value of specified Handle Graphics property

mexGetVariable (C and Fortran)

Copy of variable from specified workspace

mexGetVariablePtr (C and Fortran)

Read-only pointer to variable from another workspace

mexIsGlobal (C and Fortran)

Determine whether variable has global scope

mexIsLocked (C and Fortran)

Determine whether MEX-file is locked

mexLock (C and Fortran)

Prevent clearing MEX-file from memory

mexMakeArrayPersistent (C and Fortran)

Make array persist after MEX-file completes

mexMakeMemoryPersistent (C and Fortran)

Make memory allocated by MATLAB software persist after MEX-function completes

mexPrintf (C and Fortran)

ANSI C PRINTF-style output routine

mexPutVariable (C and Fortran)

Array from MEX-function into specified workspace

mexSet (C)

Set value of specified Handle Graphics property

mexSetTrapFlag (C and Fortran)

Control response of MEXCALLMATLAB to errors

mexUnlock (C and Fortran)

Allow clearing MEX-file from memory

mexWarnMsgIdAndTxt (C and Fortran)

Warning message with identifier

mexWarnMsgTxt (C and Fortran)

Warning message

 


这篇关于Matlab与C/C++联合编程之Matlab以MEX方式调用C/C++代码(三)的文章就介绍到这儿,希望我们推荐的文章对编程师们有所帮助!



http://www.chinasem.cn/article/609364

相关文章

C++使用栈实现括号匹配的代码详解

《C++使用栈实现括号匹配的代码详解》在编程中,括号匹配是一个常见问题,尤其是在处理数学表达式、编译器解析等任务时,栈是一种非常适合处理此类问题的数据结构,能够精确地管理括号的匹配问题,本文将通过C+... 目录引言问题描述代码讲解代码解析栈的状态表示测试总结引言在编程中,括号匹配是一个常见问题,尤其是在

Python调用Orator ORM进行数据库操作

《Python调用OratorORM进行数据库操作》OratorORM是一个功能丰富且灵活的PythonORM库,旨在简化数据库操作,它支持多种数据库并提供了简洁且直观的API,下面我们就... 目录Orator ORM 主要特点安装使用示例总结Orator ORM 是一个功能丰富且灵活的 python O

使用C++实现链表元素的反转

《使用C++实现链表元素的反转》反转链表是链表操作中一个经典的问题,也是面试中常见的考题,本文将从思路到实现一步步地讲解如何实现链表的反转,帮助初学者理解这一操作,我们将使用C++代码演示具体实现,同... 目录问题定义思路分析代码实现带头节点的链表代码讲解其他实现方式时间和空间复杂度分析总结问题定义给定

Debezium 与 Apache Kafka 的集成方式步骤详解

《Debezium与ApacheKafka的集成方式步骤详解》本文详细介绍了如何将Debezium与ApacheKafka集成,包括集成概述、步骤、注意事项等,通过KafkaConnect,D... 目录一、集成概述二、集成步骤1. 准备 Kafka 环境2. 配置 Kafka Connect3. 安装 D

Java调用DeepSeek API的最佳实践及详细代码示例

《Java调用DeepSeekAPI的最佳实践及详细代码示例》:本文主要介绍如何使用Java调用DeepSeekAPI,包括获取API密钥、添加HTTP客户端依赖、创建HTTP请求、处理响应、... 目录1. 获取API密钥2. 添加HTTP客户端依赖3. 创建HTTP请求4. 处理响应5. 错误处理6.

C++初始化数组的几种常见方法(简单易懂)

《C++初始化数组的几种常见方法(简单易懂)》本文介绍了C++中数组的初始化方法,包括一维数组和二维数组的初始化,以及用new动态初始化数组,在C++11及以上版本中,还提供了使用std::array... 目录1、初始化一维数组1.1、使用列表初始化(推荐方式)1.2、初始化部分列表1.3、使用std::

C++ Primer 多维数组的使用

《C++Primer多维数组的使用》本文主要介绍了多维数组在C++语言中的定义、初始化、下标引用以及使用范围for语句处理多维数组的方法,具有一定的参考价值,感兴趣的可以了解一下... 目录多维数组多维数组的初始化多维数组的下标引用使用范围for语句处理多维数组指针和多维数组多维数组严格来说,C++语言没

Springboot中分析SQL性能的两种方式详解

《Springboot中分析SQL性能的两种方式详解》文章介绍了SQL性能分析的两种方式:MyBatis-Plus性能分析插件和p6spy框架,MyBatis-Plus插件配置简单,适用于开发和测试环... 目录SQL性能分析的两种方式:功能介绍实现方式:实现步骤:SQL性能分析的两种方式:功能介绍记录

使用 sql-research-assistant进行 SQL 数据库研究的实战指南(代码实现演示)

《使用sql-research-assistant进行SQL数据库研究的实战指南(代码实现演示)》本文介绍了sql-research-assistant工具,该工具基于LangChain框架,集... 目录技术背景介绍核心原理解析代码实现演示安装和配置项目集成LangSmith 配置(可选)启动服务应用场景

SQL 中多表查询的常见连接方式详解

《SQL中多表查询的常见连接方式详解》本文介绍SQL中多表查询的常见连接方式,包括内连接(INNERJOIN)、左连接(LEFTJOIN)、右连接(RIGHTJOIN)、全外连接(FULLOUTER... 目录一、连接类型图表(ASCII 形式)二、前置代码(创建示例表)三、连接方式代码示例1. 内连接(I