【问题标题】:GSL - GNU Scientific Library: avoid deep copiesGSL - GNU 科学图书馆:避免深拷贝
【发布时间】:2014-12-17 20:16:45
【问题描述】:

我需要将 gsl_vector 传递给需要 C 样式数组的函数,反之亦然。

缓慢的方法(涉及深拷贝)应该是:

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

.
我能做到吗:

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

func(gx.data, gy.data, n);

【问题讨论】:

  • 是的,但唯一的授权是我自己做的。
  • 然而,我不明白为什么有一个函数有一个 inout 数组,但显然你为两个参数传递了同一个数组。这似乎不对(即函数改变了输入数组,所以应该只有一个 inout 数组)。
  • 你可能应该使用gv.size 而不是n
  • @Evert - 我修复了相同输入和输出变量的问题。
  • 你可以从一个数组开始,然后使用gsl_vector_view_array将数组转换为gsl_vector_view而不需要深拷贝。最后,您使用 .vector 将 gsl_vector_view 转换为 gsl_vector 也无需深拷贝。在 gsl 中进行您需要的计算,然后将相同的数组传递给 C 函数。

标签: arrays parameters copy gnu gsl


【解决方案1】:

您可以从 C 数组开始,然后使用 gsl_vector_view_array(文档 here)将其转换为没有深拷贝的 gsl_vector!然后,您可以在 gsl 中运行您需要的计算,然后,您可以将相同的数组传递给任何 C 函数。

// 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

【讨论】:

    猜你喜欢
    • 2013-10-31
    • 2023-03-31
    • 1970-01-01
    • 2011-10-28
    • 1970-01-01
    • 2023-03-06
    • 1970-01-01
    • 2012-08-03
    • 2012-04-12
    相关资源
    最近更新 更多