Previous Up Next

3.2  Converting ECLiPSe data to C data

There are several aspects to examining the contents of a term. These include decomposing compound terms such as lists and structures, converting simple terms to C data types and testing the types of terms.

The functions for decomposing and converting check that the type is appropriate. If it is they return EC_succeed if not they return a negative error code.

3.2.1  Converting simple ECLiPSe terms to C data types

To convert from an ECLiPSe term to a C type you first have to declare a variable with that type. For fixed size data types (you can convert to double, long and dident fixed size data types) you are responsible for allocating the memory. For strings you declare a char* variable and on conversion it will point to the internal ECLiPSe string.

In the following example we see how one can try to convert to different types. Of course normally you will know what type you are expecting so only one of these functions need be called.

    EC_word term;
    double r;
    long i;
    EC_atom did;
    char *s;
    if (EC_succeed == term.is_double(&d))
        cout << d << "\n";
    else if (EC_succeed == term.is_long(&i))
        cout << i << "\n";
    else if (EC_succeed == term.is_atom(&did))
        cout << did.Name() << "\n";
    else if (EC_succeed == term.is_string(&s))
        cout << s << "\n";
        cout << "not a simple type\n";

The term is converted by the function which returns EC_success. The functions that fail to convert will return a negative error number.

Care has to be taken with strings, these pointers point to the internal ECLiPSe string which may move or be garbage collected during an ECLiPSe execution. As a result if a string is to be kept permanently one should copy it first.

3.2.2  Decomposing ECLiPSe terms

The function ec_get_arg(index,term,&subterm) is used to get the index’th subterm of a structure. The index varies from 1 to arity of term. A list can also be decomposed this way, where the head is at index 1 and the tail at index 2.

Below we see how we would write a function to find the nth element of a list.

    int nth(const int n,const EC_word list, EC_word& el)
        EC_word tail = list;
        for (int i=1, i<n, i++)
            if (EC_fail == tail.arg(2,tail))
                return EC_fail;
        return tail.arg(1,el);

The above function actually is not limited to lists but could work on any nested structure.

Previous Up Next