Message Boards Message Boards

7
|
7512 Views
|
2 Replies
|
8 Total Likes
View groups...
Share
Share this post:

Saying hello with LibraryLink

Posted 11 years ago
In a previous post I explained how to do nothing with LibraryLink, as an exercise or
tutorial on how to extend the Wolfram Language with a very simple LibraryLink function.

In this post we go one small step further and look at how to return a result from a LibraryLink
function. In particular we are going to create function which takes no arguments, but which
returns 'Hello World' as a string to the Wolfram Language.

Here is the C code for 'HelloWorld', which we will put in a file called HelloWorld.c:

#include "WolframLibrary.h"

DLLEXPORT int HelloWorld(WolframLibraryData libData, mint Argc, MArgument *Args, MArgument Res) {
        MArgument_setUTF8String(Res,"Hello World");
        return LIBRARY_NO_ERROR;
}


This code is almost identical to the DoNothing example. The function name has changed to 'HelloWorld'
to be appropriate for this example and there is one new line of code which takes care of returning
a string ("Hello World") to the Wolfram Language function.

The function used here is MArgument_setUTF8String which sets 'Res' (which represents the returned
data) to "Hello World".

The corresponding Wolfram Language build and load code has also changed a little bit:

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


Besides the obvious name changes to use 'HelloWorld' where appropriate, the LibraryFunctionLoad calls is
now using "UTF8String" as an expected return value (which matches exactly what the C library function is
using as well).

Now we can try running this code 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[] // InputForm

Out[3]//InputForm= "Hello World"


Next, we will take a look at how to make a customized greeting using LibraryLink.
POSTED BY: Arnoud Buzing
2 Replies
@Frank, this is interesting. I haven't yet worked myself through LibraryLink+MathLink but I know this can be a useful combination.
POSTED BY: Arnoud Buzing
I used LibraryLink to set up code to call the COIN-OR Ipopt nonlinear optimization solver, with callbacks to Mathematica for function evaluations. 

https://projects.coin-or.org/Ipopt

I found that using the MathLink protocol was more userful that using mint, etc. for that application.
POSTED BY: Frank Kampas
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