| MATLAB® | ![]() |
| On this page… |
|---|
Examples of Passing Data to Shared Libraries |
The shared library interface supports all standard scalar C types. The following table shows these C types with their equivalent MATLAB types. MATLAB uses the type from the right column for arguments having the C type shown in the left column.For examples using these arguments, see Passing Primitive Types and Passing Strings.
MATLAB Primitive Types
| C Type | Equivalent MATLAB Type |
|---|---|
char, byte | int8 |
unsigned char, byte | uint8 |
short | int16 |
unsigned short | uint16 |
int | int32 |
long (32-bit) | int32 |
long (64-bit) | int64 |
unsigned int, unsigned long | uint32 |
float | single |
double | double |
char * | cstring (1xn char array) |
*char[] | cell array of strings |
The following table shows extended MATLAB types in the right column. These are instances of the MATLAB lib.pointer class rather than standard MATLAB types. For information on the lib.pointer class, see Working with Pointers. For an example using pointer arguments, see Passing a Reference.
MATLAB Extended Types
| C Type | Equivalent MATLAB Type |
|---|---|
integer pointer types (int *) | (u)int(size)Ptr |
Null-terminated string passed by value | cstring |
Null-terminated string passed by reference (from a libpointer only) | stringPtr |
Array of pointers to strings (or one **char) | stringPtrPtr |
Matrix of signed bytes | int8Ptr |
float * | singlePtr |
double * | doublePtr |
mxArray * | MATLAB array |
void * | voidPtr |
void ** | voidPtrPtr |
type ** | Same as typePtr with
an added Ptr (e.g., double ** |
Here are some important things to note about the input and output arguments shown in the Functions in library shrlibsample listing:
Many arguments (like int32 and double) are similar to their C counterparts. In these cases, you need only to pass in the MATLAB types shown for these arguments.
Some C arguments (for example, **double, or predefined structures), are different from standard MATLAB types. In these cases, you can either pass a standard MATLAB type and let MATLAB convert it for you, or you convert the data yourself using the MATLAB functions libstruct and libpointer. For more information, see Manually Converting Data Passed to Functions.
C input arguments are often passed by reference. Although MATLAB does not support passing by reference, you can create MATLAB arguments that are compatible with C references. In the Functions in library shrlibsample listing, these are the arguments with names ending in Ptr and PtrPtr. For information on using these types, see Working with Pointers.
C functions often return data in input arguments passed by reference. MATLAB creates additional output arguments to return these values. Note that in the listing in the previous section, all input arguments ending in Ptr or PtrPtr are also listed as outputs.
Nonscalar arguments must be declared as passed by reference in the library functions.
If the library function uses single subscript indexing to reference a two-dimensional matrix, keep in mind that C programs process matrices row by row while MATLAB processes matrices by column. To get C behavior from the function, transpose the input matrix before calling the function, and then transpose the function output.
When passing an array having more than two dimensions, the shape of the array might be altered by MATLAB. To ensure that the array retains its shape, store the size of the array before making the call, and then use this same size to reshape the output array to the correct dimensions. For example:
vs = size(vin) % Store the original dimensions
vs =
2 5 2
vout = calllib('shrlibsample','multDoubleArray', vin, 20);
size(vout) % Dimensions have been altered
ans =
2 10
vout = reshape(vout, vs); % Restore the array to 2-by-5-by-2
size(vout)
ans =
2 5 2Use an empty array, [], to pass a NULL parameter to a library function that supports optional input arguments. This is valid only when the argument is declared as a Ptr or PtrPtr as shown by libfunctions or libfunctionsview.
MATLAB software includes a sample external library called shrlibsample. The library is in the directory matlabroot\extern\examples\shrlib.
To use the shrlibsample library, you first need to either add this directory to your MATLAB path with the command:
addpath([matlabroot '\extern\examples\shrlib'])
or make the directory your current working directory with the command:
cd([matlabroot '\extern\examples\shrlib'])
The following example loads the shrlibsample library and displays the MATLAB syntax for calling functions in the library:
loadlibrary shrlibsample shrlibsample.h libfunctions shrlibsample -full
MATLAB displays:
Functions in library shrlibsample: [double, doublePtr] addDoubleRef(double, doublePtr, double) double addMixedTypes(int16, int32, double) [double, c_structPtr] addStructByRef(c_structPtr) double addStructFields(c_struct) c_structPtrPtr allocateStruct(c_structPtrPtr) voidPtr deallocateStruct(voidPtr) doublePtr multDoubleArray(doublePtr, int32) [lib.pointer, doublePtr] multDoubleRef(doublePtr) int16Ptr multiplyShort(int16Ptr, int32) cstring readEnum(Enum1) [cstring, cstring] stringToUpper(cstring)
For primitive types, MATLAB automatically converts any argument to the type expected by the external function. For example, you can pass a double to a function that expects to receive a byte (8-bit integer) and MATLAB does the conversion for you.
The following C function takes arguments that are of types short, int, and double:
double addMixedTypes(short x, int y, double z) {
return (x + y + z);
}You can pass all of the arguments as type double from MATLAB. MATLAB determines what type of data is expected for each argument and performs the appropriate conversions. For example, type:
calllib('shrlibsample', 'addMixedTypes', 127, 33000, pi)
MATLAB displays:
ans = 3.3130e+004
MATLAB automatically converts an argument passed by value into an argument passed by reference when the external function prototype defines the argument as a reference. For example, a MATLAB double argument passed to a function that expects double * is converted to a double reference by MATLAB.
addDoubleRef is a C function that takes an argument of type double *:
double addDoubleRef(double x, double *y, double z) {
return (x + *y + z);
}Call the function with three arguments of type double, and MATLAB handles the conversion:
calllib('shrlibsample', 'addDoubleRef', 1.78, 5.42, 13.3)
MATLAB displays:
ans = 20.5000
For arguments that require char *, you can pass a MATLAB string (a character array).
For example, the following C function takes a char * input argument:
char* stringToUpper(char *input) {
char *p = input;
if (p != NULL)
while (*p!=0)
*p++ = toupper(*p);
return input;
}libfunctions shows that you can use a MATLAB cstring for this input. Type:
libfunctions shrlibsample -full
Look for the following stringToUpper signature:
[cstring, cstring] stringToUpper(cstring)
Create a MATLAB character array, str, and pass it as the input argument:
str = 'This was a Mixed Case string';
calllib('shrlibsample', 'stringToUpper', str)
MATLAB displays:
ans = THIS WAS A MIXED CASE STRING
Although the input argument that MATLAB passes to stringToUpper resembles a reference to type char, it is not a true reference data type because it does not contain the address of the MATLAB character array, str. When the function executes, it returns the correct result, but does not modify the value in str. If you examine str, you find it is unchanged. Type:
str
MATLAB displays:
str = This was a Mixed Case string
For arguments defined as C enumerated types, you can pass either the enumeration string or its integer equivalent.
The readEnum function from the shrlibsample library returns the enumeration string that matches the argument passed in. Here is the Enum1 definition and the readEnum function in C:
enum Enum1 {en1 = 1, en2, en4 = 4} TEnum1;
char* readEnum(TEnum1 val) {
switch (val) {
case 1 :return "You chose en1";
case 2: return "You chose en2";
case 4: return "You chose en4";
default : return "enum not defined";
}
}In MATLAB, you can express an enumerated type as either the enumeration string or its equivalent numeric value. In the previous example, the TEnum1 definition declares enumeration en4 equal to 4. Call readEnum first with a string:
calllib('shrlibsample', 'readEnum', 'en4')
MATLAB displays:
ans = You chose en4
Now call it with the equivalent numeric argument 4:
calllib('shrlibsample', 'readEnum', 4)
MATLAB displays:
ans = You chose en4
Many functions in external libraries use arguments that are passed by reference. To enable you to interact with these functions, MATLAB passes what is called a pointer object to these arguments. This should not be confused with "passing by reference" in the typical sense of the term. See Working with Pointers for more information.
You can create a NULL pointer to pass to library functions in the following ways:
Pass a 0 as the argument.
Use the libpointer function:
p = libpointer; % no arguments
p = libpointer('string') % string argumentp = libpointer('stringPtr') % pointer to a string argumentUse the libstruct function:
p = libstruct; % no arguments
Under most conditions, MATLAB software automatically converts data passed to and from external library functions to the type expected by the external function. However, you may choose to convert your argument data manually. Circumstances under which you might find this advantageous are:
When you pass the same piece of data to a series of library functions, you can convert it once manually before the call to the first function rather than having MATLAB convert it automatically on every call. This reduces the number of unnecessary copy and conversion operations.
When you pass large structures, you can save memory by creating MATLAB structures that match the shape of the C structures used in the external function instead of using generic MATLAB structures. The libstruct function creates a MATLAB structure modeled from a C structure taken from the library. See Working with Structures for more information.
When an argument to an external function uses more than one level of referencing (e.g., double **), you must pass a reference created using the libpointer function rather than relying on MATLAB to convert the type automatically.
To load C++ libraries, you must define the function prototypes as extern "C" in the library header file. For example, the following function prototype from the file mex.h shows the syntax to use for each function:
#ifdef __cplusplus
extern "C" {
#endif
void mexFunction(
int nlhs,
mxArray *plhs[],
int nrhs,
const mxArray *prhs[]
);
#ifdef __cplusplus
}
#endifAnother approach to using C++ libraries is to generate a prototype M-file that contain aliases for the mangled C++ function names. Use the original (premangled) function names as the aliases for the C++ functions. Generate the M-file with the mfilename option of the loadlibrary function and then determine which functions in the library you want to make available by defining aliases for these functions.
![]() | Calling Functions in Shared Libraries | Working with Pointers | ![]() |
| © 1984-2008- The MathWorks, Inc. - Site Help - Patents - Trademarks - Privacy Policy - Preventing Piracy - RSS |