58 lines
2.6 KiB
C#
58 lines
2.6 KiB
C#
using System;
|
|
using System.Runtime.InteropServices;
|
|
using System.Text;
|
|
|
|
public static class ComNativeWrapper
|
|
{
|
|
private const string Dll = "ComNative"; // имя файла в Plugins/x86_64 без .dll
|
|
|
|
// --- Порты (Unicode) ---
|
|
[DllImport(Dll, CallingConvention = CallingConvention.Cdecl, CharSet = CharSet.Unicode)]
|
|
public static extern int Serial_ListPortsLength();
|
|
|
|
[DllImport(Dll, CallingConvention = CallingConvention.Cdecl, CharSet = CharSet.Unicode)]
|
|
public static extern int Serial_ListPorts(StringBuilder buffer, int bufferChars);
|
|
|
|
// --- Открытие/закрытие ---
|
|
[DllImport(Dll, CallingConvention = CallingConvention.Cdecl, CharSet = CharSet.Unicode)]
|
|
public static extern int Serial_Open(string portName, int baud, int dataBits, int parity, int stopBits,
|
|
int readTimeoutMs, int writeTimeoutMs);
|
|
|
|
[DllImport(Dll, CallingConvention = CallingConvention.Cdecl)]
|
|
public static extern int Serial_Close(int handleId);
|
|
|
|
[DllImport(Dll, CallingConvention = CallingConvention.Cdecl)]
|
|
public static extern int Serial_CloseAll(); // NEW
|
|
|
|
// --- Запись/чтение (строкой) ---
|
|
[DllImport(Dll, CallingConvention = CallingConvention.Cdecl, CharSet = CharSet.Ansi)]
|
|
public static extern int Serial_WriteStringUTF8(int handleId, string utf8, int appendNewline);
|
|
|
|
// byte[]-вариант к той же native-функции (EntryPoint), чтобы избежать маршаллинга StringBuilder
|
|
[DllImport(Dll, CallingConvention = CallingConvention.Cdecl, EntryPoint = "Serial_ReadLineUTF8")]
|
|
public static extern int Serial_ReadLineUTF8_bytes(int handleId, byte[] buffer, int bufferSize);
|
|
|
|
// --- Ошибка (Unicode) ---
|
|
[DllImport(Dll, CallingConvention = CallingConvention.Cdecl, CharSet = CharSet.Unicode)]
|
|
public static extern int Serial_GetLastErrorW(StringBuilder buffer, int bufferChars);
|
|
|
|
public static string GetLastError()
|
|
{
|
|
int need = Serial_GetLastErrorW(null, 0);
|
|
var sb = new StringBuilder(Math.Max(need, 1));
|
|
int r = Serial_GetLastErrorW(sb, sb.Capacity);
|
|
return (r < 0) ? $"err({r})" : sb.ToString();
|
|
}
|
|
|
|
public static string[] ListPorts()
|
|
{
|
|
int need = Serial_ListPortsLength();
|
|
if (need <= 1) return Array.Empty<string>();
|
|
var sb = new StringBuilder(need);
|
|
int r = Serial_ListPorts(sb, sb.Capacity);
|
|
if (r < 0) return Array.Empty<string>();
|
|
string joined = sb.ToString();
|
|
return string.IsNullOrWhiteSpace(joined) ? Array.Empty<string>() : joined.Split(';');
|
|
}
|
|
}
|