4

I just noticed std::byte in the C++ 17.

I am asking this question because I use the code below to send byte array to C++ to play audio sound.

C#:

[DllImport ("AudioStreamer")]
public static extern void playSound (byte[] audioBytes);

C++:

#define EXPORT_API __declspec(dllexport)
extern "C" void EXPORT_API playSound(unsigned char* audioBytes)

With the new byte type in C++ 17, it looks like I might be able to do this now:

C#:

[DllImport ("AudioStreamer")]
public static extern void playSound (byte[] audioBytes);

C++:

#define EXPORT_API __declspec(dllexport)
extern "C" void EXPORT_API playSound(byte[] audioBytes)

I am not sure if this will even work because the compiler I use does not support byte in C++ 17 yet.

So, is std::byte in C++ 17 equivalent to byte in C#? Is there a reason to not use std::byte over unsigned char* ?

Programmer
  • 121,791
  • 22
  • 236
  • 328
  • Worth a read http://stackoverflow.com/questions/43143318/stdbyte-on-odd-platforms. It starts with odd platforms, but the answers cover all the basics. – Richard Critten Apr 08 '17 at 10:25
  • C# **requires** that bytes are exactly 8 bits, but if you're interworking C++ and C#, you can safely assume that C++ too is using 8-bit bytes – MSalters Sep 19 '17 at 12:31

2 Answers2

2

According to C++ reference,

Like the character types (char, unsigned char, signed char) std::byte can be used to access raw memory occupied by other objects.

This tells me that you can freely replace

unsigned char audioBytes[]

with

std::byte audioBytes[]

in a function header, and everything is going to work, provided that you plan to treat bytes as bytes, not as numeric objects.

Sergey Kalinichenko
  • 714,442
  • 84
  • 1,110
  • 1,523
  • Given Microsoft's record of bringing their compilers in compliance with C and C++ standards, the question of using `std::byte` for interoperability with C# will remain a purely theoretical topic for a considerable amount of time. – Sergey Kalinichenko Apr 08 '17 at 10:28
  • I will be treating bytes as bytes and this sounds promising. I will try my best to modify my code and test this on GCC compiler that supports byte and will update you today. – Programmer Apr 08 '17 at 10:36
0

std::byte is equivalent to both unsigned char and char in C++ in a sense that it is a type to represent 1 byte of raw memory.

If you used unsigned char* in your interface, you can easily replace it with std::byte.

In your C# code this will result in no changes at all, on the C++ side this will make your type system more strict (which is a good thing) due to the fact that you will not be able to treat your std::bytes as text characters or as small integers.

Of course this is C++17 feature which may or may not be properly supported by your compiler.

Ap31
  • 3,244
  • 1
  • 18
  • 25