5
|
8215 Views
|
3 Replies
|
5 Total Likes
View groups...
Share

# 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 andreturning the square of that integer. But in general the types of what you pass into functions and whatyou return don't have to match. Here is an example of a function which takes a real number as an argumentand returns a boolean value (true or false) depending on whether this number is 'close' to Pi (where closenessis 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:  #define _USE_MATH_DEFINES #include  #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; };        MArgument_setInteger(Res,result);        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 ina real value passed from the CloseToPi function, after which we compute its closeness to Pi. If it is close we set theboolean 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) hereis not the same as the return value ("Boolean"). This file is called CloseToPi.m:Needs["CCompilerDriver`"];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]= FalseIn[3]:= CloseToPi[3.147]Out[3]= TrueIn[4]:= CloseToPi[5]Out[4]= FalseNote 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.
3 Replies
Sort By:
Posted 11 years ago
 @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 11 years ago
 Yes, I see what's you're doing.  That's what I get for only looking at code and not reading the explanation.
Posted 11 years ago
 I don't think you need Get["CloseToPi.m"].  Also, I think it's a good idea to use LibraryFunctionUnload when you're done.