Message Boards Message Boards

3 Replies
5 Total Likes
View groups...
Share this post:

Writing a boolean function with LibraryLink

Posted 11 years ago
In a previous post I explained how to do basic integer math using LibraryLink by passing in integers and
returning the square of that integer. But in general the types of what you pass into functions and what
you return don't have to match. Here is an example of a function which takes a real number as an argument
and returns a boolean value (true or false) depending on whether this number is 'close' to Pi (where closeness
is defined as being within 0.01 away from Pi).

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

 #include <math.h>
 #include "WolframLibrary.h"
 DLLEXPORT int CloseToPi(WolframLibraryData libData, mint Argc, MArgument *Args, MArgument Res) {
         double x;
         mbool result;
         x = MArgument_getReal(Args[0]);
        if( fabs(x-M_PI)<0.01 ) { result = 1; } else { result = 0; };
        return LIBRARY_NO_ERROR;

The #define here is only required on Windows, to help it know about M_PI (The C value for Pi). In this code we read in
a real value passed from the CloseToPi function, after which we compute its closeness to Pi. If it is close we set the
boolean result variable to 1 (True) and if not we set it to 0 (False).

The Wolfram Language build and function loading code is different from previous examples in that the argument (Real) here
is not the same as the return value ("Boolean"). This file is called CloseToPi.m:

lib = CreateLibrary[{"CloseToPi.c"},"CloseToPi"];
CloseToPi = LibraryFunctionLoad[lib,"CloseToPi",{Real},"Boolean"];

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["CloseToPi.m"]
 In[2]:= CloseToPi[1.2]
 Out[2]= False

In[3]:= CloseToPi[3.147]

Out[3]= True

In[4]:= CloseToPi[5]

Out[4]= False

Note that if you call CloseToPi with an integer argument, then this integer automatically gets converted to its nearest real number.

In the next post we will take a look at how to calculate the mean value of a list passed in by your Wolfram Language function.
POSTED BY: Arnoud Buzing
3 Replies
@Frank, I find it convenient to put the boiler plate commands in a .m file so I don't have to retype them. That's the only reason I put them there. But maybe I misunderstand your comment?
POSTED BY: Arnoud Buzing
Yes, I see what's you're doing.  That's what I get for only looking at code and not reading the explanation.
POSTED BY: Frank Kampas
I don't think you need Get["CloseToPi.m"].  Also, I think it's a good idea to use LibraryFunctionUnload when you're done.
POSTED BY: Frank Kampas
Reply to this discussion
Community posts can be styled and formatted using the Markdown syntax.
Reply Preview
or Discard

Group Abstract Group Abstract