The correct way to initialize std :: array from a C array

I get an array from the C API, and I would like to copy it to std :: array for later use in my C ++ code. So what is the right way to do this?

I 2 uses for this, one of them:

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

And this one

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

But that seems pretty awkward. Is there an idiomatic way to do this that is apparently not related to memcpy? For MyClass, maybe I'm better off with a constructor that takes a std :: array that moves to a member, but I also can't figure out how to do this.?

+4
source share
1 answer

You can use the algorithm std::copydeclared in the header <algorithm>. for example

#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() );

If f.kasme- this is really an array, you can also write

std::copy( std::begin( f.kasme ), std::end( f.kasme ), a.begin() );
+5

Source: https://habr.com/ru/post/1613895/


All Articles