1
$\begingroup$

If I wanted to return a list from a MathLink function, how could I do that?

:Begin:
:Function:  add
:Pattern:   add[x:{___Real}, y:{___Real}]
:Arguments: { x, y }
:ArgumentTypes: { Real64List, Real64List }
:ReturnType: Manual
:End:


/*What return type goes here?*/ add(double* x, int length, double* y, int length2)
{
    double* sum = new double[length];
    for(int i=0;i<length; ++i)
    {
        sum[i] = x[i] + y[i];
    }
    return /*What do I return? */;
}
$\endgroup$
1
$\begingroup$

Ok so after mucking around in a lot of documentation I found out that the proper way to do this is to:

  • Set the ReturnType to Manual
  • Set the return type of the function to void
  • Call "MLPutReal64List"

C++ code:

#include "mathlink.h"

void add(double* x, int length, double* y, int length2)
{
    double* sum = new double[length];
    for(int i=0;i<length; ++i)
    {
         sum[i] = x[i] + y[i];
    }
    MLPutReal64List(stdlink, sum, length);
}
int main(int argc, char *argv[]) {
    return MLMain(argc, argv);
}

Template file:

:Begin:
:Function:  add
:Pattern:   add[x:{___Real}, y:{___Real}]
:Arguments: { x, y }
:ArgumentTypes: { Real64List, Real64List }
:ReturnType: Manual
:End:    
$\endgroup$
  • $\begingroup$ You should delete [] sum; after MLPutReal64List. C++ is not garbage collected. $\endgroup$ – Szabolcs Aug 30 '17 at 10:28

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.