How can I pack a struct in a message?



next up previous contents
Next: The compiler can't Up: Writing Programs Previous: Is message order

How can I pack a struct in a message?

Unfortunately, that's a hard thing to do in C without some sort of preprocessing before compilation. You'll need to write special pack and unpack routines for any struct you want to pack, for example:

    struct foo {
        int *values;        /* vector of (length) elements */
        short length;
        double perf;
        int flags;
    };

    int
    pkfoo(foop, cnt, std)
        struct foo *foop;   /* vector of foos */
        int cnt;            /* number of foos */
        int std;            /* stride between foos */
    {
        int cc;

        while (cnt-- > 0) {
            if (cc = pvm_packf("%hd %*d %lf %d",
                               foop->length,
                               (int)foop->length,
                               foop->values,
                               foop->perf,
                               foop->flags))
                return cc;
            foop += std;
        }
        return PvmOk;
    }

    int
    upkfoo(foop, cnt, std)
        struct foo *foop;
        int cnt;
        int std;
    {
        int cc;

        while (cnt-- > 0) {
            if ((cc = pvm_unpackf("%hd", &foop->length))
            ||  (!(foop->values = (int*)malloc(foop->length
                                               * sizeof(int)))
                 && (cc = PvmNoMem))
            ||  (cc = pvm_packf("%*d %lf %d",
                                (int)foop->length,
                                foop->values,
                                &foop->perf,
                                &foop->flags)))
                return cc;
            foop += std;
        }
        return PvmOk;
    }

Note that if the struct contains only primitive types (or other structs that contain only primitive types), that is, no pointers, and you're passing it to a host of identical type (not just one with the same data representations (because they might not build structs the same way)), you could get away with:

    struct foo foo1;

    pvm_pkbyte((char*)&foo1, n * sizeof(struct foo), 1);
    ...
    pvm_upkbyte((char*)&foo1, n * sizeof(struct foo), 1);



Bob Manchek
Fri Mar 3 15:08:11 EST 1995