-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathCommon.cs
55 lines (46 loc) · 1.52 KB
/
Common.cs
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
// Copyright (C) 2024 - Nordic Space Link
using System;
namespace NordicSpaceLink.IIO
{
internal static class Common
{
public unsafe static string ErrorDescription(nint error)
{
const int buffersize = 1024;
Span<byte> buffer = stackalloc byte[buffersize];
fixed (byte* bufferPtr = buffer)
NativeMethods.iio_strerror(error, bufferPtr, buffersize);
return buffer.CString();
}
public static nint CheckError(nint result, string message = "")
{
if (result < 0)
{
if (message == "")
throw new Exception($"Error: {ErrorDescription(-result)}");
throw new Exception($"{message}. Error: {ErrorDescription(-result)}");
}
return result;
}
internal static int StrLen(Span<byte> str)
{
var idx = str.IndexOf((byte)0);
if (idx < 0)
return str.Length;
return idx;
}
internal static string CString(this Span<byte> str)
{
var len = StrLen(str);
return System.Text.Encoding.ASCII.GetString(str[..len]);
}
internal unsafe static string ConstCString(byte* ptr, int max_length)
{
if (ptr == null)
return "";
var str = new Span<byte>(ptr, max_length);
var len = StrLen(str);
return System.Text.Encoding.ASCII.GetString(str[..len]);
}
}
}