In a
previous post I explained how to return strings of text from a LibraryLink function. In this post we are going to expand
a bit on this idea by passing in a string from your Wolfram Language function and returning a customized string. The function
will be called 'Greetings' and it takes a single string argument which is returned but prepended with the word 'Greetings' and
followed by an exclamation mark.
Here is the C code for 'Greetings', which we will put in a file called Greetings.c:
#include <stdio.h>
#include "WolframLibrary.h"
DLLEXPORT int Greetings(WolframLibraryData libData, mint Argc, MArgument *Args, MArgument Res) {
char *name;
char result[1024];
name = MArgument_getUTF8String(Args[0]);
sprintf(result,"Greetings %s!",name);
MArgument_setUTF8String(Res,result);
return LIBRARY_NO_ERROR;
}
This code is similar to the Hello World example program, with the following additions: It defines a string variable called 'name'
which is used to pass in the first argument (Args[0]) from the Greetings function, using MArgument_getUTF8String. The second addition
is the result variable string (allocated for up to 1,024 characters). The sprintf function formats the value of the name variable
into the result variable. After result is set it is fed back using the MArgument_setUTF8String.
The Wolfram Language build and function loading code is also similar to the Hello World example, with the notable change of specifying
that the function now needs to pass in a string ( {"UTF8String"} ):
Needs["CCompilerDriver`"];
lib = CreateLibrary[{"Greetings.c"},"Greetings"];
Greetings = LibraryFunctionLoad[lib,"Greetings",{"UTF8String"},"UTF8String"];
Now we can try running this code in the Wolfram Language, using any name (less than 1,024 characters):
Mathematica 10.0 for Microsoft Windows (64-bit)
Copyright 1988-2013 Wolfram Research, Inc.
In[1]:= Get["Greetings.m"]
In[2]:= Greetings["Maria"]
Out[2]= Greetings Maria!
Now, let's take a look at
an example that uses numbers instead of strings.