stringlist handling in the C-API

Hello,

I want to use string list handling in the CAPI.

On Interaction with the Wolfram Language—Wolfram Documentation

there are all available data types for using to transfer data from mathematica to my shared library.

Available are:

“Boolean” mbool Boolean
…

{base,rank,memory} MTensor tensor with specified memory management

LibraryDataType[SparseArray,…] MSparseArray sparse array

“UTF8String” char * UTF8 string

LinkObject WSLINK arguments and result written to WSTP ´
…

So I can only use char * with

MArgument_getUTF8String(Args[n]);

or is there another possibility to manage lists of string. The strange thing is that there are lists available in mathematica see:

and

So how can I transfer such a list to my c++ shared library?

It would be great if you could help me.

Best regards,

Roland

Hello,

is there anybody who can help me or has an idea?

How is it possible to transfer string lists to or from a dynamic library? It seems that LinkObject could be a possibility. Has anybody experience with that or an idea that can help me?

Best regards,

Roland

Use LinkObject-based passing, i.e. transfer the strings through a MathLink connection.

You would need to use the following functions:

  • MLTestHead to check that you are receiving a List, and to retrieve the number of elements
  • MLGetUTF8String or one of the analogous functions to get the string with te desired encoding
  • Once you’re done using it, free it with the corresponding function, e.g. MLReleaseUTF8String

The mlstream.h header that comes with my LTemplate package makes this task considerably easier. There is an example included that shows how to receive an arbitrary number of string arguments, concatenate them, and return the result. I’ll copy it here:

The StrCat.h C++ header file (must be in the current working directory):

#include <mlstream.h>
#include <string>
#include <vector>

struct StrCat {
    // Concatenate an arbitrary number of strings
    void strcat(MLINK link) {
        mlStream ml(link, "strcat");

        // We do not check for the number of arguments;
        // instead, we read all arguments into a string vector
        std::vector<std::string> vec;
        ml >> vec;

        // Concatenate the strings
        std::string result;
        for (const auto &el : vec)
            result += el;

        ml.newPacket();
        ml << result;
    }
};

Mathematica code:

Needs["LTemplate`"]

template = LClass["StrCat", {LFun["strcat", LinkObject]}];

CompileTemplate[template]
LoadTemplate[template]

obj = Make[StrCat]

obj@"strcat"["foo", "bar", "baz"]
(* "foobarbaz" *)