11

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. ?

3

1 Answer 1

7

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() );
Sign up to request clarification or add additional context in comments.

4 Comments

@binary01 It is my mistake.:) I deleted that part of the post.:)
This feels a bit risky. I'd let the number of characters that is being copied be determined by the target, instead of the source, to avoid array overflow. This can be done with std::copy_n: std::copy_n(f.kasme, a.size(), a.begin());
@CarloWood The same problem can occur if the size of std::array is less than the size of the array. So your proposal in general does not make sense.:)
Reading random memory is generally less a security risk than writing to random memory. My remark is about the last line: std::copy( std::begin( f.kasme ), std::end( f.kasme ), a.begin() ); which would overwrite memory if the size of kasme is larger than a. Otherwise you need error handling, or make it a feature that a is only read partially if the size of kasme is less than that of a, however - the way OP asked the question, the size of kasme_ is not known.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.