c++11 object that can be passed as "double (*)[4]"

70 views Asked by At

I need to call an function in an external library that has a signature:

void fn(double (*values)[4]);

but I would like to pass an object like std::vector<std::array<double, 4>> and it must be c++11 compliant. How would I call this function?

2

There are 2 answers

3
Jas On BEST ANSWER

With this:

std::vector<std::array<double, 4>> my_array;
...
// Function call:
fn((double(*)[4]) &my_array[array_index][0]);
2
R Sahu On

How would I call this function?

The most clean way to call the function is:

  1. Create an array of four doubles.
  2. Fill up the data in the array from an appropriate source.
  3. Pass the address of the array to the function

double array[4];

// Fill up the array with data
for (size_t i = 0; i < 4; ++i )
{
   array[i] = ...;
}

fn(&array);

In order to be able to call the function when you have a std::vector<std::array<double, 4>>, you can create couple of wrapper functions.

void fn_wrapper(std::array<double, 4>>& in)
{
  double array[4];

  // Fill up the array with data
  for (size_t i = 0; i < 4; ++i )
  {
     array[i] = in[i];
  }

  fn(&array);

  // If you fn modified array, and you want to move those modifications
  // back to the std::array ...
  for (size_t i = 0; i < 4; ++i )
  {
     in[i] = array[i];
  }
}

void fn_wrapper(std::vector<std::array<double, 4>>& in)
{
   for ( auto& item : in )
   {
      fn_wrapper(item);
   }
}