Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Proper way to initialize a std::array from a C array

I'm getting an array from a C API, and I'd like to copy this to a std::array for further use in my C++ code. So what is the proper way of doing that ?

I 2 uses for this, one is:

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

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 this feels rather clunky. Is there an idiomatic way of doing this, that presumably doesn't involve memcpy ? For MyClass` perhaps I'm better off with the constructor taking a std::array that get moved into the member but I can't figure out the proper way of doing that either. ?

like image 979
binary01 Avatar asked Oct 30 '15 20:10

binary01


1 Answers

You can use algorithm std::copy declared in 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 is indeed an array then you can also write

std::copy( std::begin( f.kasme ), std::end( f.kasme ), a.begin() );
like image 110
Vlad from Moscow Avatar answered Sep 25 '22 17:09

Vlad from Moscow