可以作为 "double (*)[4]" 传递的 c++11 对象

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

我需要在具有签名的外部库中调用一个函数:

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

但我想传递一个像 std::vector<std::array<double, 4>> 这样的对象,它必须符合 c++11。我该如何调用这个函数?

How would I call this function?

最简洁的函数调用方式是:

  1. 创建一个包含四个双精度数的数组。
  2. 从适当的来源填充数组中的数据。
  3. 将数组的地址传递给函数

double array[4];

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

fn(&array);

为了能够在您拥有 std::vector<std::array<double, 4>> 时调用该函数,您可以创建几个包装函数。

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);
   }
}

有了这个:

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