Main Content

<library>Initialize[WithHandlers]

Initialize MATLAB Runtime instance associated with library

Description

bool libraryInitialize() creates a MATLAB® Runtime instance associated with the generated C/C++ shared library library using the default print and error handlers.

Call this function in your C/C++ application after calling mclInitializeApplication and before calling any of the compiled functions exported by the library.

example

bool libraryInitializeWithHandlers(mclOutputHandlerFcn error_handler, mclOutputHandlerFcn print_handler) creates a MATLAB Runtime instance associated with library and allows you to specify functions to handle error messages and printed text. The functions passed to libraryInitializeWithHandlers are installed in the MATLAB Runtime instance and called whenever error text or regular text outputs.

example

bool libraryInitializeWithKey(const char* session_key) creates a MATLAB Runtime instance associated with library and allows you to specify a hex encoded 64 byte AES decryption key. This syntax allows the user to provide the decryption key at runtime using the C++ API rather than a MEX loader. For more details, see mcc -k.

example

bool libraryInitializeWithHandlersAndKey(mclOutputHandlerFcn error_handler, mclOutputHandlerFcn print_handler, const char* session_key) creates a MATLAB Runtime instance associated with library and allows you to specify an error handler, print handler, and hex encoded AES decryption key.

example

Examples

collapse all

Initialize the MATLAB Runtime instance associated with a C/C++ library named libtriangle.

Call the initialization function for the C library libtriangle in the main function of your C application code.

if (!libtriangleInitialize())
{
    fprintf(stderr, 
            "An error occurred while initializing: \n %s ",
            mclGetLastErrorMessage());
    return -2;
}

If initialization fails, an error message is printed to standard error.

By default, applications and shared libraries generated using MATLAB Compiler SDK™ send printed output to standard output and error messages to standard error. To change this behavior, write your own error and print handlers and pass them to libraryInitializeWithHandlers. To use a default handler, pass in mclDefaultPrintHandler or mclDefaultPrintHandler.

For a complete example, see the files located in matlabroot\extern\examples\compilersdk\c_cpp\catcherror.

Write a custom print handler function in your C/C++ application. This example code is written in C and uses two helper functions, StartMatlabOutput and EndMatlabOutput, to wrap a banner around the printed output.

static int PrintHandler(const char *s)
{
    /* Declare and initialize all variables */
    int len = 0;
    const char * prefix = "* ";
    int written = 0;

    if (s == NULL)
    {
        return 0;
    }

    len = strlen(s);

    /* DISP adds two carriage returns. Suppress the last one. */
    if (len >= 2 && s[len-1] == '\n' && s[len-2] == '\n')
    {
        len = len-1;
    }
    
    if (emitPrefix)
    {
        fwrite(prefix, sizeof(char), strlen(prefix), stdout);
    }
    
    written = fwrite(s, sizeof(char), len, stdout);

    if (s[len-1] == '\n')
    {
        emitPrefix = true;
    }
    else
    {
        emitPrefix = false;
    }

    return written;
}

static void StartMatlabOutput()
{
    const char *startBanner = "******** Start MATLAB output *******\n";
    emitPrefix = false;
    PrintHandler(startBanner);
}

static void EndMatlabOutput()
{
    const char *endBanner = "********* End MATLAB output ********\n";
    emitPrefix = false;
    PrintHandler(endBanner);
}

Write a custom error handler function.

static char LastError[2048];

static int ErrorHandler(const char *s)
{
    int len = 0;
    len = strlen(s);
    LastError[0] = '\0';
    strcpy(LastError, s);
    return len+1;
}

In your main function, after initializing variables, pass the print and error handlers to the libraryInitializeWithHandlers function.

if (!libcatcherrorInitializeWithHandlers(ErrorHandler, PrintHandler))
{
    fprintf(stderr,"Could not initialize the library.\n");
    return -2;
}
else
{
    /* Call the library function. */
    if (mlfRealacos(1, &out, in1))
    {
        /* Display the return value of the library function */
        printf("realacos(%6.4f) = \n", in1val);
        StartMatlabOutput();
        mlfReveal(out);
        EndMatlabOutput();
    }
    else
    {
        printf("Disaster! An unexpected error occurred.\n");
        printf("Error:\n%s\n", LastError);
    }

    /* Call the library termination routine */
    libcatcherrorTerminate();
        
    /* Free the memory allocated for the input variables. */
    mxDestroyArray(in1); 
    in1 = 0;
    mxDestroyArray(in2); 
    in2 = 0;
}

As an alternative to providing a MEX loader file at compile time, you can specify a decryption key in your C++ application using the libraryInitializeWithKey function.

Obtain an AES encryption key. For instance, you can generate a key using openssl at the command line.

openssl rand -hex 64 -out appkey.key

Create a C++ shared library using mcc. Specify the encryption key you generated using the -k option. For more details, see mcc -k.

 mcc -W cpplib:libappwithkey appwithkey.m -k 'file=appkey.key'

In the main function of your C++ application, retrieve your decryption key. For example, you could retrieve the key from an AWS® CloudHSM cluster. Pass in the hex encoded key as an argument for the initialize function libappwithkeyInitializeWithKey.

if (!mclInitializeApplication(NULL, 0))
    {
        printf("Failed to initialize application.\n");
        return -1;
    }

    /* Retrieve the decryption key. */
    ...
    
    if (!libappwithkeyInitializeWithKey(“<key_value>”)) 
    {
        printf("Failed to initialize libappwithkey.\n");
        return -2;
    }
else
{
    /* Call the library function. */
    ...
}

If initialization fails, an error message is printed to standard error.

Input Arguments

collapse all

Library name, specified as part of the function name. The library must be a C/C++ shared library generated by MATLAB Compiler SDK.

Example: libmatrix

Error handler function, specified as a custom user-written function or mclDefaultErrorHandler. The function must take a string and return the number of characters printed. For more details, see Print and Error Handling Functions.

Example: myErrorHandler

Print handler function, specified as a custom user-written function or mclDefaultPrintHandler. The function must take a string and return the number of characters printed. If the string sent to the standard error output stream does not end with a carriage return, the function must add one. For more details, see Print and Error Handling Functions.

Example: myPrintHandler

AES decryption key, specified as a hex encoded AES key with a 64 character file size.

For more details, see mcc -k.

Example: mykey.txt

Output Arguments

collapse all

Initialization result, returned as a boolean value. Result indicates whether or not mcli initialization was successful. If the function returns false, calling any compiled functions results in unpredictable behavior.

Version History

Introduced in R2009a