c# fixed byte 배열에 대이터 넣기
[StructLayout(LayoutKind.Sequential, Pack = 1)]
unsafe struct TestStruct
{
public fixed byte TestField1[6];
public fixed byte TestFiels2[1];
}
unsafe void SetString(string value, byte* field)
{
byte[] bytes = Encoding.GetEncoding(949).GetBytes(value);
for (int i = 0; i < bytes.Length; i++)
{
field[i] = bytes[i];
}
}
unsafe string GetString(byte* field, int length)
{
byte[] bytes = new byte[length];
for (int i = 0; i < length; i++)
{
bytes[i] = field[i];
}
return Encoding.GetEncoding(949).GetString(bytes);
}
unsafe void SetGet()
{
Encoding.RegisterProvider(CodePagesEncodingProvider.Instance);
TestStruct block = new();
SetString("123456", block.TestField1);
SetString("A", block.TestFiels2);
string value = GetString(block.TestField1, 6);
}
예를 들어 ls증권 api의 경우 오래 전 버전의 비주얼 스투디오로 만들어 utf를 쓰지 않고 unified hangul code로 보낸다. 이 코드를 code page 949(cp949)나 windows-949 등으로 부른다. 949는 그냥 여러 코드 패이지들 가운데 구분하기 위한 identifier다. 오래된 거고 지금은 거의 쓰지 않는다.
최근 버전의 .네트는 utf만 지원하여 위 코드 패이지로 인코드나 디코드를 하려면 encoding provider라는 걸 등록해야 한다. 한 번 하면 전역으로 작동한다.
byte*는 바이트 포인터로서 unsafe context에서만 쓸 수 있다.