Message Boards Message Boards

3
|
4298 Views
|
0 Replies
|
3 Total Likes
View groups...
Share
Share this post:

Working with a variable number of arguments in LibraryLink

Posted 11 years ago
In a previous post I showed how you can use WolframLink (formerly known as MathLink) as a mechanism to pass in and return
general Wolfram Language expressions. Here we are going to look at a slightly more complicated example where we pass in
a variable number of integer arguments, multiply them together and return the result (Multiply.c):

 #include "WolframLibrary.h"
 
 DLLEXPORT int Multiply(WolframLibraryData libData, MLINK mlp) {
         const char* fun;
         int i,arglen;
         mint product = 1;
         mint arg;
 
         MLGetFunction(mlp, &fun, &arglen);
        for(i=0; i<arglen; i++) {
                MLGetInteger(mlp, &arg);
                product *= arg;
        }
        MLNewPacket(mlp);
        MLPutInteger(mlp,product);

        return LIBRARY_NO_ERROR;
}


The first WolframLink call, MLGetFunction, reads the head of the expression (always "List" in the case of LibraryLink)
and obtains the number of elements (arglen). Next we loop over those arguments, which are all assumed to be integers.
For every integer we read (MLGetInteger) we multipy that number into the end product. At the end of the loop we return
the end product using MLPutInteger.

Here is the corresponding build and function load code (Multiply.m):

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


And here is how the code runs in the Wolfram Language:

 Mathematica 10.0 for Microsoft Windows (64-bit)
 Copyright 1988-2013 Wolfram Research, Inc.
 
 In[1]:= Get["Multiply.m"]
 
 In[2]:= Multiply[2]
 
 Out[2]= 2
 
In[3]:= Multiply[2,3]

Out[3]= 6

In[4]:= Multiply[2,3,4]

Out[4]= 24
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