I am having trouble connecting MATLAB to a C++ .dll library. First I tried using the loadlibrary function in MATLAB, but this gave many syntax errors when building the _thunk_pcwin64 file (I assume because loadlibrary only works with C). I am using R2011a on 64-bit Windows 7.
Next, I tried using mex to interface with the library. My code (named attotest.cpp) is given at the end. The function compiles fine in MATLAB with mex using Microsoft Visual C++ 2010 Express. When I try to call attotest() though, I get a segmentation violation. Debugging the function with mex -g, I find that hGetProcIDDLL is listed as 0x00 {unused=???} with "CXX0030: Error: expression cannot be evaluated" in the debugger. My guess is that LoadLibrary is somehow not being called/evaluated properly (EDIT: Upon further research using GetLastError(), I have found that the error generated when calling LoadLibrary() is 193 "note a valid win32 application"). When I compile a C++ program with the exact same lines of code, it loads the .dll fine and calls the function as expected.
(By the way, if I comment out the line "Int32 numDev =…" and initialize numDev independently to a constant, then the function runs fine in MATLAB. So the LoadLibrary and FreeLibrary functions are apparently being called in a way that doesn't crash anything, though they aren't really connecting with the .dll as I want them to.
EDIT: one more comment: PositionerInfo is a struct defined in hvpositionerv2.h).
Any suggestions on what is wrong, what I could do to fix this error, or what else I could try to call this .dll from within MATLAB?
thanks!
#include "mex.h"#include <cstdio>#include <cstdlib>#include <windows.h>#include "hvpositionerv2.h"void attotest(double y[]){ HINSTANCE hGetProcIDDLL = LoadLibrary("C:\\hvpositionerv2.dll"); typedef int (_stdcall *PROCSTRUCTIN)(PositionerInfo**); PROCSTRUCTIN funcPosCheck = (PROCSTRUCTIN)GetProcAddress(HMODULE (hGetProcIDDLL), "PositionerCheck"); PositionerInfo* pi = 0; Int32 numDev = (funcPosCheck)(&pi); FreeLibrary(hGetProcIDDLL); y[0]=(double) numDev;}void mexFunction( int nlhs, mxArray *plhs[], int nrhs, const mxArray *prhs[] ){ double *x,*y; mwSize mrows,ncols; /* Check for proper number of arguments. */ if(nrhs!=0) { mexErrMsgTxt("Zero input required."); } else if(nlhs>1) { mexErrMsgTxt("Too many output arguments."); } /* Create matrix for the return argument. */ plhs[0] = mxCreateDoubleMatrix(1,1, mxREAL); /* Assign pointers to each input and output. */ y = mxGetPr(plhs[0]); attotest(y);}
Best Answer