octave-maintainers
[Top][All Lists]
Advanced

[Date Prev][Date Next][Thread Prev][Thread Next][Date Index][Thread Index]

Implementing loadlibrary, calllib, etc.


From: John Swensen
Subject: Implementing loadlibrary, calllib, etc.
Date: Tue, 23 Mar 2010 22:46:36 -0400

I recently had a colleague who used the Matlab loadlibrary, calllib, etc. 
functions for accessing stepper motor controller (rather than writing a MEX 
function).  I started looking to see if this was available in Octave, as it 
seems quite useful, and found that it is not implemented.  I then started 
searching for a way of building dynamic function argument lists in C/C++, so 
one could dlopen a shared library, parse a header file for function names with 
corresponding return type and parameters, and then calling into the shared 
library from Octave.

I found a library called FFCALL that seems to do exactly what I was hoping for. 
 It is implemented for quite a few architectures (hopefully most of the 
most-commonly used platforms for Octave) and provides a way to build up dynamic 
arguments lists.  I prototyped a quick test to prove to myself that this might 
work.
FUNCTION IN SHARED LIBRARY
extern "C" int function1(int a, double b, float c, int len, double* array)
{
  cout << "a: " << a << "   b: " << b << "   c: " << c << endl;
  cout << "Array: (";
  for (int i = 0 ; i < len ; i++)
  {
    cout << array[i];
    if (i< len-1)
      cout << ", ";
  }
  cout << ")" << endl;

  return 13;
}

CODE TO LOAD LIBRARY AND CALL WITH A CONSTRUCTED ARGUMENT LIST USING THE FFCALL 
LIBRARY
  int a = 1;
  double b = 2.5;
  float c = 3.14159;
  int len = 5;
  double array[] = {1,2.5,3.14159,5.1,11.11};

  libhandle = dlopen ("./testlib.dylib", RTLD_NOW);
  if (!libhandle) {
    cout << dlerror() << endl;
    exit(1);
  }

  fcnhandle = dlsym(libhandle, "function1");
  if ((error = dlerror()) != NULL)  {
    cout << error << endl;
    exit(1);
  }

  int retval;
  av_alist argList;
  av_start_int(argList, fcnhandle, &retval);
  av_int(argList, a);
  av_double(argList, b);
  av_float(argList, c);
  av_int(argList, len);
  av_ptr(argList, double*, array);
  av_call(argList);

  dlclose(libhandle);

So now it seems that I should be able to do this sort of thing, but lack one 
critical skill: regular expressions.  I think I could come up with a very 
inelegant way of parsing a header file to extract function names, return types, 
and parameters types, but would be open to some help from one of those regular 
expression wizards out there in this part of the process.  Once that is 
complete, I think I can implement the loadlibrary, callib, etc. quite 
accurately.  (I suppose I could also take the time to learn regular expressions 
well, but that might take more time than I have right now).

John Swensen




reply via email to

[Prev in Thread] Current Thread [Next in Thread]