0

I need to interface C++ code to a C library. I have a std::array:

std::array<uint8_t, buffer_size> send;

Stuff gets written to send, and then I need to pass a pointer to this data to a C function. I'm not sure the best way to do that.

Here is my best guess:

write(fd, &send[0], size); // c function
Mike
  • 51
  • 5
  • 10
    just use `send.data()` See in the documentation [here](https://en.cppreference.com/w/cpp/container/array) –  Nov 11 '21 at 00:07
  • Note that your best guess is a pretty good one. Frank's suggestion is foolproof, though. Can't fail. One addition: Use `buffer.size()` instead of `size` if you want to write the whole array. Just like with Frank's suggestion, you'll get fewer surprises. – user4581301 Nov 11 '21 at 00:11
  • @user4581301 Since "stuff" is getting written to `send` from other code, it makes sense to have a separate `size` variable to indicate how much "stuff" was actually written to `send`, and thus is available to pass to `write()`. If the "stuff" is not equal to `buffer_size` then using `send.size()` will be wrong to use in that situation. – Remy Lebeau Nov 11 '21 at 00:17
  • Can't argue with that since it's what I thought I wrote. – user4581301 Nov 11 '21 at 00:21
  • In my case I am using only part of the array, thus size is != .size(). Can you tell me how .data() is better than address of first element? I would like to understand at a low level because that is how I am using it. – Mike Nov 11 '21 at 15:40
  • @Mike: There's no reason to use the address of the first element, since `.data()` gives you exactly that. Using actual words avoids making people who read the code have to understand a particular idiom. The code is self-describing. – Nicol Bolas Nov 11 '21 at 16:01

0 Answers0