Search code examples
arrayscswig

Return unbounded C array as type[]


In a C API for my library I have some set of functions with signatures like this

size_t get_data(unsigned char* buffer, size_t buffer_len);
// or
size_t get_float_data(float* buffer, size_t buffer_len);

this functions return number of elements in internal arrays (so you can pass NULL to buffer and get real array length) and buffer is destination buffer, and buffer_len is number available elements in buffer.

Typical usage is:

size_t data_size = get_data(NULL, 0);
unsigned char* data = (unsigned char*)malloc(data_size);
get_data(data, data_size);
//or
size_t float_data_size = get_float_data(NULL, 0);
float* float_data = (float*)malloc(float_data_size * sizeof(float));
get_float_data(float_data, float_data_size);

And I would like wrap this function in SWIG for next signature

byte[] get_data();
float[] get_float_data();

for java and c#.

I found a lot of examples if unbounded C array is input, but can't find anything for output. And I do not understand how to change signature of target functions with typemap's without to concretize a function name.


Solution

  • I found a lot of examples if unbounded C array is input, but can't find anything for output.

    There is a reason for that : you can't it is illegal in c (and c++)

    char f() [] { // the actual syntax
        //whatever you want to do with it
    }
    

    but since an array (unbound or not) is also a pointer so you can do

    char * f() {
        //whatever you want to do like before
    }
    

    if you want to also return the size of it the best way is just to make a struct containing the size and the pointer.

    Also all the function that take array as input actualy take the pointer to the array.