26
Figure 8 M-Module Driver Example Using Buffers
3.4.2.2
Arrays
Alien arrays build upon buffers by adding an extra layer of safety and elements that describe the
array. The function
alien.array(type, length)
allocates an array where type is the Alien
type of the elements and length is the number of elements in the array. Once allocated, the user
may use
arr.type
to get the type of the elements,
arr.length
to get the number of elements in
the array,
arr.size
to get the size in bytes of each element and
arr.buffer
to get the
underlying buffer. The user can access the elements of an array directly with
arr[i]
. The
example in Figure 9, perform the same exact function as the example in Figure 8 but with arrays
instead of buffers.
require "alien"
local libm228 = alien.load("/usr/scripts/user/libm228.so")
-----------------------------------------------------------
-- Function Prototypes
-----------------------------------------------------------
local m228_Init = libm228.m228_Init
m228_Init:types("int", "int", "int", "int", "ref int")
local m228_ReadFifoBuffer = libm228.m228_ReadFifoBuffer
m228_ReadFifoBuffer:types("int", "int", "int", "int", "pointer",
"pointer", "pointer", "ref int")
local m228_Close = libm228.m228_Close
m228_Close:types("int", "int")
-----------------------------------------------------------
-- Start of Script --
-----------------------------------------------------------
result, handle = m228_Init(1,1,1, 0)
time_buff = alien.buffer(256 * alien.sizeof("int"))
real_buff = alien.buffer(256 * alien.sizeof("double"))
raw_buff = alien.buffer(256 * alien.sizeof("short"))
result, num_read = m228_ReadFifoBuffer(handle, 0, 256, time_buff,
real_buff, raw_buff, 0)
for offset=0, 256, 1
do
print(string.format('0x%x', raw_buff:get((i *
alien.sizeof("short")) + 1, "short"))
end
m228_Close(handle)
print("Done!")