从C数组

时间:2015-10-30 20:23:29

标签: c++

我从C API获取数组,并且我想将其复制到std :: array以便在我的C ++代码中进一步使用。那么这样做的正确方法是什么?

I 2用于此,一个是:

struct Foo f; //struct from C api that has a uint8_t kasme[32] (and other things)

c_api_function(&f);
std::array<uint8_t, 32> a;
memcpy((void*)a.data(), f.kasme, a.size());

这个

class MyClass {
  std::array<uint8_t, 32> kasme;
  int type;
public:
  MyClass(int type_, uint8_t *kasme_) : type(type_)
  {
      memcpy((void*)kasme.data(), kasme_, kasme.size());
  }
  ...
}
...
MyClass k(kAlg1Type, f.kasme);

但这感觉相当笨重。有没有惯用的方法,这可能不涉及memcpy?对于MyClass`也许我会更好 采用std :: array的构造函数被移入成员但我无法弄清楚这样做的正确方法。 ?

1 个答案:

答案 0 :(得分:6)

您可以使用标头std::copy中声明的算法<algorithm>。例如

#include <algorithm>
#include <array>

//... 

struct Foo f; //struct from C api that has a uint8_t kasme[32] (and other things)

c_api_function(&f);
std::array<uint8_t, 32> a;
std::copy( f.kasme, f.kasme + a.size(), a.begin() );

如果f.kasme确实是一个数组,那么你也可以写

std::copy( std::begin( f.kasme ), std::end( f.kasme ), a.begin() );
相关问题