Many functions in external libraries pass arguments by reference.
When you pass by reference, you pass a pointer to
the value. In
the function signature, pointer arguments have names ending in
Although MATLAB® does not support passing by reference, you can
create a MATLAB argument, called a lib.pointer object,
that is compatible with a C pointer. This object is an instance of
Often, you can simply pass a MATLAB variable
(passing an argument by value), even when the signature for that function
declares the argument to be a pointer. There are times, however, when
it is useful to pass a
You want to modify the data in the input arguments.
You are passing large amounts of data, and you want to control when MATLAB makes copies of the data.
The library stores and uses the pointer so you want
the MATLAB function to control the lifetime of the
C represents characters as 8-bit integers. To use a MATLAB character array as an
input argument, convert
the string to the proper type and create a
str = 'string variable'; vp = libpointer('voidPtr',[int8(str) 0]);
[int8(str) 0] creates the null-terminated
string required by the C function. To read the string, and verify
the pointer type, enter:
ans = string variable ans = voidPtr
converts an argument passed by value into an argument passed by reference
when the external function prototype defines the argument as a pointer. Call a function that takes a
a string as an input argument using the following syntax.
Although MATLAB converts the argument from a value to a pointer, it must be of the correct type.
In general, MATLAB passes a valid memory address each time
you pass a variable to a library function. Use a
in cases where the library stores the pointer and accesses the buffer
In these cases, ensure that MATLAB has
control over the lifetime of the buffer and prevent copies of the data from being
made. The following pseudo-code is
an example of asynchronous data acquisition that shows how to use
lib.pointer in this situation.
Suppose an external library
myLib has the
AcquireData(int points,short *buffer) IsAquisitionDone(void)
buffer is declared as follows:
First, create a
lib.pointer to an array of 99
BufferSize = 99; pBuffer = libpointer('int16Ptr',zeros(BufferSize,1));
Then, begin acquiring data and wait in a loop until it is done:
calllib('myLib','AcquireData,BufferSize,pbuffer) while (~calllib('myLib','IsAcquisitionDone') pause(0.1) end
The following statement reads the data in the buffer:
result = pBuffer.Value;
When the library is done with the buffer, clear the MATLAB variable: