环境:vs2015、Matlab2020
VS2015中建立工程,
建立工程如下两图所示
在头文件和源文件中分别添加头文件和源文件(代码如下所示)
头文件matdll.h文件
#pragma once
#ifndef MATDLL_H
#define MATDLL_H
#ifdef __cplusplus
extern "C"
{
#endif
//自定义输出函数
__declspec(dllexport) double add(double x, double y);
#ifdef __cplusplus
}
#endif
#endif
源文件:mat.cpp
#include "matdll.h"
double add(double x, double y)
{
return (x + y);
}
在Matlab中调用
首先需要将动态链接库MatDll.dll文件拷贝至目录
test.m文件内容
mex -setup;
mex -setup c++;
loadlibrary('MatDll.dll','matdll.h');
calllib('MatDll','add',3.4,2.0);
Matlab运行结果如下
需要注意的问题:
红色框处都问两个下划线
动态链接库.dll文件在Matlab可读的目录下