How to mex this simple .cu file?

This is a very simple cuda file, which is basically a mex interface with cuda code together. All I want is to make it callable to MATLAB

#include "mex.h"
#include <cuda.h>
#include <cuda_runtime.h>

__global__ void test_cuda_vs(int a, int b)

void mexFunction(int nlhs, mxArray *plhs[],
    int nrhs, const mxArray *prhs[])
        plhs[0] = mxCreateDoubleMatrix(1,1,mxREAL);
        double* out = mxGetPr(plhs[0]);

How should I compile it to make test_cuda can be called by MATLAB like a built-in function?

I have

system('nvcc -c -gencode arch=compute_30,code=sm_30 -gencode arch=compute_35,code=sm_35')

generating the obj file. Should I use mex to do next step? I am not sure how to do that, and what is the command line roughly?

Or it cannot, and I should do it in another way? Thanks

PS: I have
Windows 7 64-bit
CUDA 5.5, 6.0, 6.5

That walks you through the whole process (assuming you are using Visual Studio).

The CUDA code needs to be in a separate .cu file and called via an extern “C” function. You can call cuBLAS,cuFFT or cuSPARSE directly from a mexFunction however.

This is terrific, Thanks!

You can do a two-step process of first having nvcc generate the fatbin and stuff it into a .cpp file, then Matlab’s mex will be happy to compile/link that. Here’s a slightly genericized snippet from one of my Makefiles:

        nvcc $(NVCC_OPTS) $(NVCC_INCL) $(PAR_INCL) -cuda -o stuff.cpp
        mex $(MEX_OPTS) -c stuff.cpp
stuff: cudaCommon.o stuff.o
        mex $(MEX_OPTS) $(PAR_LDIR) $(PAR_LIBS) -cxx $@.o -o $@ $(MEX_LDIR) $(MEX_LIBS)

I’ve had this complain if cudaCommon.o contains just device rather than device inline functions though, the linker claimed that I had multiple instances of a function definition.