Problem integrating C++ code into Matlab


I am trying to do a simple program to access a XEM3001 board from Matlab. I followed the C++ tutorial and now I can upload a bitfile and communicate with the board using C++ code.

Now I want to do the same from Matlab using the mex compiler. I am using Visual Studio 10, Matlab R2010a, and the XEM3001_v2. I updated the mex compiler options to be able to call the VS10 compiler. I am compiling x64 code and it works well as a stand alone application (from the DOS command window).

My mex compiler works and compiles the files I want, but this is my problem: I can only access the board the first time and then the board is not released so the second time I run my compiled mex module it cannot find the board.

Now I have two programs and one of them loads the DLL and can access the FPGA board the first time. The second time there is some problem because the DLL is already loaded and Matlab crashes.

So I have another program that does not open the DLL and it compiles ok and the okCUSBcontrolpanel object is created. Is just that the code cannot find the board.

The second time I get a 0 from getDeviceCount() and -15 as the error from OpenBySerial().

Do you have any hint on how to release the board? I tried deleting the xem pointer from the C++ code and it crashes matlab. Also I found an UnregisterAll() method in the documentation but it seems to be discontinued in the last version.

In my Console Application the board is released after the program ends and I can rerun it many times, but it seems that in Matlab the DLL is holding it even after the mex command ends.



PS. I also tried to use okFrontPanelDLL_FreeLib(), but the second time you try to run the code it crashes like the DLL was not really unloaded.

Are you calling the okCFrontPanel_Destruct method?

— Begin quote from Opal Kelly Support;3312

Are you calling the okCFrontPanel_Destruct method?

— End quote

Thanks a lot! That solved the problem.

As a side note you need to call the destructor for the Matlab/mex code only. It is not needed for the Console Application. Now I just use the code as in the C++ code with a xem->~okCUsbFrontPanel(); at the end. Also I just needed to link the .obj files compiled by VS10:

mex Source3.cpp ybusfunctions.obj okFrontPanelDLL.obj

ybusfunctions.obj is an object file with my own code and okFrontPanelDLL.obj is the FrontPanel object code. And Source3.cpp is my C++/mex file.

These are the headers for the mex file, I had to put my headers before the mex headers and add 3lines to avoid a compiling error:

// putting everything else you need

#include “okFrontPanelDLL.h”
#include “ybusfunctions.h”

// to avoid multiple definitions error
#ifdef _CHAR16T
#define CHAR16_T

// mex files

Actually, the operating system will clean some things up for you when an application closes. Since things are self-contained inside another application, you can’t quite be as sloppy with object and instances there.