通过网络发送2darray

时间:2014-10-04 16:52:06

标签: c sockets networking endianness

说我想通过网络发送二维数组:

int array_to_send[2][4] = {{1, 2, 3, 4}, {5, 6, 7, 8}};

我将这个数组保存在通用数组中,因为我不知道编译时的类型:

struct generic_array_type {
    /* Pointer to array */
    void *array;
    /* Size of one element */
    size_t elem_size;
    /* Number of dimensions, max 3 */
    size_t num_dimensions;
    /* Dimensions */
    size_t dimensions[3];
};
typedef struct generic_array_type genarray_t;

然后我像这样填充结构:

genarray_t _2dgarray;

/* Fill in data */
_2dgarray.array             = array_to_send;
_2dgarray.elem_size         = sizeof(int);
_2dgarray.num_dimensions    = 2;
_2dgarray.dimensions[0]     = 2;
_2dgarray.dimensions[1]     = 4;

现在我的问题是:因为int受系统的endianess影响,我想将每个元素转换为网络顺序。我是这样做的:

/* Now, compute the size of the array in bytes */
// Simplified for this example
size_t garray_size  = _2dgarray.dimensions[0] * _2dgarray.dimensions[1] * _2dgarray.elem_size;

    /* Go through each element */
    {
        unsigned char *ptr          = _2dgarray.array;
        void (*swapBytes)(void *)   = NULL;

        switch (_2dgarray.elem_size) {
            case 2:
                swapBytes = swapBytes2;
            break;

            case 4:
                swapBytes = swapBytes4;
            break;

            default:
                fprintf(stderr, "Byte swap not implemented for %zu\n", _2dgarray.elem_size);
            break;
        }

        for (size_t i = 0; i < garray_size; i += _2dgarray.elem_size) {
            /* Pointer to element */
            void *element   = ptr + i;

            /* Swap bytes */
            swapBytes(element);
        }
    }

    /* Now the array should have network order endianess, convert it to char buffer */
    char buffer[garray_size];

    memcpy(buffer, (char *)_2dgarray.array, garray_size);

    /* Send "buffer" over network... */

byteswapping函数:

void swapBytes2(void *ptr)
{
    uint16_t val        = *(uint16_t *)ptr;
    *(uint16_t *)ptr    = _bswap16(val);
}

void swapBytes4(void *ptr)
{
    uint32_t val        = *(uint32_t *)ptr;
    *(uint32_t *)ptr    = _bswap32(val);
}

它有效,但我真的不确定这是否是正确的方法。特别是“memcpy”部分,它将数组转换为char数组。

0 个答案:

没有答案