필터 지우기
필터 지우기

Passing C function pointers when working with Mex files?

조회 수: 2 (최근 30일)
gujax
gujax 2012년 3월 1일
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

채택된 답변

James Tursa
James Tursa 2012년 3월 1일
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
gujax
gujax 2012년 3월 2일
Thanks James,
Sounds good.
And yes, I was wrong. You can have function pointers as a part of the structure.

댓글을 달려면 로그인하십시오.

추가 답변 (0개)

카테고리

Help CenterFile Exchange에서 Write C Functions Callable from MATLAB (MEX Files)에 대해 자세히 알아보기

Community Treasure Hunt

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

Start Hunting!

Translated by