本文参照:《GPU与MATLAB混合编程》一书
使用CUDA实现简单向量加法
环境配置
软件:VS2019+CUDA v11.1+Matlab r2022a
本文是在Matlab中实现,未使用VS
环境配置及cuda安装参照网上他人教程
mex接口
Matlab提供mex函数,可以将C/C++的代码转换为.mexw64格式的文件供调用。
使用Mex函数需要引入头文件:#include "mex.h"
mexfunction
相当于C语言中的主函数main( ),当作matlab与其他交互的桥梁,进行读取和写入输入/输出的参数。
/* The gateway function */
void mexFunction(int nlhs, mxArray *plhs[], int nrhs, const mxArray *prhs[])
{
/* variable declarations here */
/* code here */
}
nlhs : 输出参数的个数
plhs : 输出参数的指针数组,指向输出参数
nrhs : 输入参数的个数
prhs : 输入参数的指针数组,指向输入参数
这一步最重要的是不能漏掉 const
,否则编译时会报错。
函数文件
1.AddVectors.h
#ifndef __ADDVECTORS_H__
#define __ADDVECTORS_H__
extern void addVectors(float* A, float* B, float* C, int size);//函数在其他文件中执行,在此先进行声明
#endif // __ADDVECTORS_H__
2.AddVectors.cu
#include "AddVectors.h"
#include "mex.h"
__global__ void addVectorsMask(float*A, float*B, float*C, int size)
{
int i=blockIdx.x;
if(i>=size)
return;
C[i]=A[i]+B[i