Message Boards Message Boards

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

Squaring integers with LibraryLink

Posted 11 years ago
In a previous post I explained how to pass in and return strings using LibraryLink. In this post we will be doing something
similar, but with passing in an integer value, performing a basic arithmetical operation on it and returning the result. In particular
we will be squaring the integer being passed in.

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

 
 #include "WolframLibrary.h"
 
 DLLEXPORT int Squared(WolframLibraryData libData, mint Argc, MArgument *Args, MArgument Res) {
         mint x;
         mint result;
         x = MArgument_getInteger(Args[0]);
         result = x*x;
         MArgument_setInteger(Res,result);
        return LIBRARY_NO_ERROR;
}


Note how this code is very similar to the previous Greetings example, except that we are now passing in integers (using MArgument_getInteger)
and returning integers (MArgument_setInteger). The squaring operation is performed by x*x and should work for small enough values of x. This
is then assigned to 'result' which is passed back to the Wolfram Language function.


The Wolfram Language build and function loading code is also similar to the Greetings example, but now we need to specify Integer
instead of "UTF8String" (note that Integer is a Wolfram Language symbol here and not a string).



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


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["Squared.m"]
 
 In[2]:= Squared[4]
 
 Out[2]= 16

In[3]:= Squared[42]

Out[3]= 1764


Note that if you call the function Squared with a value that is too large, an error will be issued:


In[4]:= Squared[58934754879783459483793]

LibraryFunction::cfsa: Argument 58934754879783459483793 at position 1 should be a machine-size integer.

Out[4]= LibraryFunction[<>, Squared, {Integer}, Integer][58934754879783459483793]


In the next post we will take a look at how to create a function which returns a boolean answer (True/False).
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