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:

#define _USE_MATH_DEFINES

#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; };

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 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:

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]= 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.