Created
July 14, 2021 00:55
-
-
Save brianmed/57e630174a7b600b8cce0727ee4fe92b to your computer and use it in GitHub Desktop.
tcgetattr Marshalling fun for .Net 5
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
using System; | |
using System.Runtime.InteropServices; | |
namespace SysRplSerialPort | |
{ | |
[StructLayout(LayoutKind.Explicit)] | |
public struct TermiosStruct | |
{ | |
[MarshalAs(UnmanagedType.U4), FieldOffset(0)] | |
public uint c_iflag; | |
[MarshalAs(UnmanagedType.U4), FieldOffset(4)] | |
public uint c_oflag; | |
[MarshalAs(UnmanagedType.U4), FieldOffset(8)] | |
public uint c_cflag; | |
[MarshalAs(UnmanagedType.U4), FieldOffset(12)] | |
public uint c_lflag; | |
[MarshalAs(UnmanagedType.ByValArray, SizeConst = 33), FieldOffset(16)] | |
public byte[] c_cc; | |
[MarshalAs(UnmanagedType.U4), FieldOffset(52)] | |
public uint c_ispeed; | |
[MarshalAs(UnmanagedType.U4), FieldOffset(56)] | |
public uint c_ospeed; | |
public static TermiosStruct Default | |
{ | |
get => new TermiosStruct { c_cc = new byte[33] }; | |
} | |
} | |
class Program | |
{ | |
[DllImport("libc", CallingConvention = CallingConvention.Cdecl, EntryPoint = "tcgetattr")] | |
public static extern int tcgetattr(int fd, ref TermiosStruct term); | |
[DllImport("libc", EntryPoint = "open")] | |
private static extern int open(string fileName, int mode); | |
[DllImport("libc", EntryPoint = "ioctl", SetLastError = true)] | |
private static extern int ioctl(int fd, int request, int data); | |
[DllImport("libc", EntryPoint = "read", SetLastError = true)] | |
private static extern int read(int handle, byte[] data, int length); | |
[DllImport("libc", EntryPoint = "write", SetLastError = true)] | |
private static extern int write(int handle, byte[] data, int length); | |
// constants for i2c | |
private static int O_RDWR = 2; | |
private static int O_NOCTTY = 0400; | |
static void Main(string[] args) | |
{ | |
Console.WriteLine("Hello World!"); | |
var term = TermiosStruct.Default; | |
// this writes 33 correctly | |
Console.WriteLine(term.c_cc.Length); | |
tcgetattr(open("/dev/ttyS0", O_RDWR | O_NOCTTY), ref term); | |
// exception here as c_cc is now null | |
Console.WriteLine(term.c_cc.Length); | |
} | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment