Passing C function pointers when working with Mex files?

2 visualizzazioni (ultimi 30 giorni)
Hi, I have a Matlab GUI accessing a USB device with its .dll The GUI accesses the USB data often i.e., it keeps calling the USB for data and plots it almost in real time. However, here is the problem. The first time GUI calls the USB and asks it to initialize and returns. Then after a while it asks the USB to start and send out data and this it does in a loop.
Now I tried to write a mex function for calling the USB and retrieving the data.
void init_USB_Mex(char *inputbf)
{
USBINI Initialize;
HINST hDLL;
THis function loads the dll and initializes using
hDLL = LoadLibrary;
and
Initialize = (USBINI) GetProcAddress(hDLL, "_fname");
and
then
Initialize()
}
It has a similar C++ routine for Start (Start_USB_Mex).
So my mex gateway routine keeps calling these functions using a check for input buf. If input buf says 'initialize' it runs the first C program and as the case maybe for subsequent calls.
However, for every call to Start, it has to go through the GetProcAddress followd by Start and then calling another Stop function to stop the USB. If I do not stop the USB and keep calling the Start function, I get segmentation error and Matlab hangs.
So how can I using mex keep calling Start-Stop without having to go through the GetProc... routine.
Is there a way I can define :static START start; in the mex function
I have up until now used the Matlab calllib functions. But now I want to move on to using C library GetProcAdd.
Structures in C do not have function members but C++ classes have those. And so if I have to pass member functions to mex is there a way? Hope I was clear in my problem statement. Thanks

Risposta accettata

James Tursa
James Tursa il 1 Mar 2012
You can put all of your variables that you want to retain values at the top level of your code (i.e., global ... outside of any function scope). They will maintain their values in between mex function calls. So call the mex function with some special input (e.g., your 'initialize' string) to get the dll loaded and initialized and initialize these global variables. Once you load the dll it should stay loaded as long as your process is still running. On subsequent calls just use the global variables. One would typically have a mexAtExit function registered as well to clean things up if the mex function is cleared.
Also, why do you imply that C structures cannot have function pointers as part of the structure? They most certainly can. Or did I misunderstand you?
  1 Commento
gujax
gujax il 2 Mar 2012
Thanks James,
Sounds good.
And yes, I was wrong. You can have function pointers as a part of the structure.

Accedi per commentare.

Più risposte (0)

Categorie

Scopri di più su Write C Functions Callable from MATLAB (MEX Files) in Help Center e File Exchange

Community Treasure Hunt

Find the treasures in MATLAB Central and discover how the community can help you!

Start Hunting!

Translated by