Message Boards Message Boards

0
|
3899 Views
|
0 Replies
|
0 Total Likes
View groups...
Share
Share this post:

Hello World revisited using WolframLink in LibraryLink

Posted 11 years ago
In previous LibraryLink code examples we have used only basic data types (integers, reals, strings, booleans) and
their tensor versions (lists of reals, matrices of integers, etc.). We will now look at working with general Wolfram
Language expressions within LibraryLink functions. For this we need to use WolframLink (formerly known as MathLink) as
a way to read general expressions and write back general expressions.

Here is a very simple HelloWorld example, similar to the previous HelloWorld example in functionality but differing
in implementation in that it uses a WolframLink to write back an expression containing the string "Hello World!" (HelloWorld.c):

 #include "WolframLibrary.h"
 
 DLLEXPORT int HelloWorld(WolframLibraryData libData, MLINK mlp) {
         long len;
         MLTestHead(mlp, "List", &len);
 
         MLNewPacket(mlp);
         MLPutString(mlp,"Hello World!");
 
        return LIBRARY_NO_ERROR;
}


Normally, for WolframLink programs, we would need to #include "mathlink.h", but because WolframLibrary already depends on this
we don't have to explicitly include it here.

When using WolframLink to pass in arguments, the arguments come in a list, i.e. MyFunction[arg1,arg2,arg3,...] appears as
List[arg1,arg2,arg3,...] on the WolframLink expression 'mlp'. Since we're not passing in any arguments to the HelloWorld[]
function, we simply detect that the incoming expression has a head of "List" and discard it.

Next we start a new (return) packet (MLNewPacket) and put the "Hello World!" on the return expression.

Here is the corresponding build and function load code (HelloWorld.m):

Needs["CCompilerDriver`"];
lib = CreateLibrary[{"HelloWorld.c"},"HelloWorld"];
HelloWorld = LibraryFunctionLoad[lib,"HelloWorld", LinkObject, LinkObject];


Note that here the function arguments and return values are completely handled by link objects. Aside from that
everything else is the same.

And here is how the code runs in the Wolfram Language:

 Mathematica 10.0 for Microsoft Windows (64-bit)
 Copyright 1988-2013 Wolfram Research, Inc.
 
 In[1]:= Get["HelloWorld.m"]
 
 In[2]:= HelloWorld[]
 
 Out[2]= Hello World!
 
In[3]:= HelloWorld[1,2,3]

Out[3]= Hello World!


Note that since here we now handle the function arguments in our C code, we can call HelloWorld with any kind
of argument (since we're discarding all the function arguments).
POSTED BY: Arnoud Buzing
Reply to this discussion
Community posts can be styled and formatted using the Markdown syntax.
Reply Preview
Attachments
Remove
or Discard

Group Abstract Group Abstract