0

I need to pass a gsl_vector to a function that expects a C style array, and vice versa.

The slow approach (which involves a deep copy) should be:

const size_t n = 4;
gsl_vector gx;    // initialize and fill
gsl_vector gy;    // initialize
double in[n], out[n];

for(size_t i = 0; i < n; ++i)
    in[i] = gsl_vector_get(gx, i);

func(in, out, n);

for(size_t i = 0; i < n; ++i)
    gsl_vector_set(gy, i, out[i]);

.
Can I do:

const size_t n = 4;
gsl_vector gx;    // initialize and fill
gsl_vector gy;    // initialize

func(gx.data, gy.data, n);
Pietro
  • 12,086
  • 26
  • 100
  • 193
  • Yes, but the only authority is that I've done this myself. –  Oct 22 '14 at 11:39
  • I don't understand, however, why there is a function that has an `in` and `out` array, but apparently you're passing it the same array for both arguments. That doesn't seem right (i.e., the function alters the input array, so there should simply be one `inout` array). –  Oct 22 '14 at 11:41
  • And you probably should use `gv.size` instead of `n`. –  Oct 22 '14 at 11:42
  • @Evert - I fixed the issue about the same input and output variable. – Pietro Oct 22 '14 at 14:13
  • @Evert - I used `n` since it is needed to resize the vectors and it is needed by `func()`. – Pietro Oct 22 '14 at 14:14
  • "resize the vectors". I take that to mean that `gx.data` (or `gy.data`) can have more elements than 4? You may want to check that `n <= gx.size && n <= gy.size` though. –  Oct 22 '14 at 14:21
  • 2
    You can start with an array, and then use gsl_vector_view_array to convert the array to gsl_vector_view without a deep copy. Finally, you use .vector to convert gsl_vector_view to gsl_vector also without a deep copy. Do the calculation you need in gsl and then pass the same array to the C function. – Vivian Miranda Oct 23 '14 at 03:10
  • @ViniciusMiranda: if you write it as an answer, I will accept it. – Pietro Nov 09 '14 at 00:34

1 Answers1

4

You can start with a C array and then convert it to a gsl_vector without deep copies by using gsl_vector_view_array (documentation here)! Then, you can run the calculation you need in gsl and, after that, you may pass the same array to any C function.

// something like
int size = 10
double* xarray = new double[size] // you can use malloc here. Irrelevant to the answer
gsl_vector_view xarray_gsl = gsl_vector_view_array ( xarray, size );
// Now xarray_gsl.vector is a gsl_vector that you can send to any gsl routine
// After that you can send the original xarray to any C function
// No deep copies are involved
Vivian Miranda
  • 2,467
  • 1
  • 17
  • 27