22
3.4
CALLING M-MODULE DRIVERS
The scripting utilities include a Lua library known as
Alien
that allows a Lua script to call
dynamic libraries (,so, dll, etc.). Using Alien, we can make calls to any of C&H Technologies’
standard M-Module drivers. Alien uses the Foreign Function Interface (FFI) library to
dynamically call shared library functions. Alien was written by a third party and like Lua, is
open source software.
The alternative to using Alien is to write a “wrapper” around the driver that makes the library a
native Lua component. Tools do exist that can automatically generate a wrapper however they
still require knowledge of Lua C components and the tools necessary to cross compile the source
code for ARM based Linux. By using Alien, we can utilize M-module drivers as-is without the
need of building more software.
The downside to using Alien is that ANSI-C code is inherently not “safe.” In other words, the
code can perform actions that result in undefined behaviors, such as dereferencing an invalid
address. In a C program or library this will result in a crash of the application. In contrast, Lua
is a safe language where no matter the code, the behavior is defined. Alien is written to be as
safe as possible; however it is still easy to crash Lua from within a library, thus, to avoid
frustration, care must be taken when calling drivers using Alien.
Crashes due to a misbehaving C library typically only occur during development. Once a
program is debugged, it is rare that a crash will occur. Recovering from a crash typically
involves rebooting or power-cycling the EM405-8. A system reboot can be performed remotely
via the EM405-8 webpage under the Status/Control link.
3.4.1
Using Alien to Call M-Module Drivers
The usage of Alien to call M-Module drivers can be divided into three basic steps:
1.
Load the driver library
2.
Define function prototypes for the functions to be called
3.
Perform function calls.
To load a driver library from within a script, we must first load the Alien Lua module using the
require
function like we would any other Lua library. In addition to the alien library, we may
also sometimes load a library called “alien.struct.” This library can be used to convert Lua
values to and from C structures. It is a good idea, in most cases, to
require
alien.struct by
default. Once Alien is loaded, we can use the
alien.load
function to load the M-Module
driver. The Lua source code below shows how to perform these steps. Note that there are
multiple ways to perform the same tasks in Lua source code. For clarity, we a have chosen to
present the most straight forward way.
require “alien”
require “alien.struct”
libm228 = alien.load(“/usr/scripts/user/libm228.so”)