i have this code function in C++ to convert different objects to bytes array:
template <typename T>
static void GetBytesArrayFrom(T value, BYTE *out_array)
{
union BytesConverter
{
T value;
BYTE bytes_array[sizeof(T)];
};
BytesConverter bc;
bc.value = value;
memcpy(out_array, bc.bytes_array, sizeof(T));
}
now i am trying to make same function in C#, but have a problem:
public void GetBytesFrom<T>(T value, byte[] out_array) where T : object
{
struct BytesConverter
{
[FieldOffset(0)]
T value; //T is unknown here
[FieldOffset(0)]
byte[] bytes_array = new byte[sizeof(T)]; //and here
}
int test = 0;
}
and it appear to be i can’t define struct inside function at all.
How then it possible to do same cool conversion function in C#?
1 Answer