-
Notifications
You must be signed in to change notification settings - Fork 13
/
NFCContext.cs
76 lines (61 loc) · 2.07 KB
/
NFCContext.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
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using SharpNFC.PInvoke;
using System.Runtime.InteropServices;
namespace SharpNFC
{
public class NFCContext : IDisposable
{
protected IntPtr contextPointer;
public NFCContext()
{
//var ptr = Marshal.AllocHGlobal(Marshal.SizeOf(typeof(IntPtr)));
//Functions.nfc_init(ptr);
//contextPointer = (IntPtr)Marshal.PtrToStructure(ptr, typeof(IntPtr));
//Marshal.FreeHGlobal(ptr);
Functions.nfc_init(out contextPointer);
}
public List<string> ListDeviceNames()
{
int someUnknownCount = 8;
IntPtr connectionStringsPointer = Marshal.AllocHGlobal(Constants.NFC_BUFSIZE_CONNSTRING * someUnknownCount);
var devicesCount = Functions.nfc_list_devices(contextPointer, connectionStringsPointer, (uint)someUnknownCount);
var devices = new List<string>();
for (int i = 0; i < devicesCount; i++)
{
devices.Add(Marshal.PtrToStringAnsi(connectionStringsPointer + i * Constants.NFC_BUFSIZE_CONNSTRING));
}
Marshal.FreeHGlobal(connectionStringsPointer);
return devices;
}
public virtual NFCDevice OpenDevice(string name)
{
IntPtr devicePointer;
try
{
devicePointer = Functions.nfc_open(contextPointer, name);
if(devicePointer == IntPtr.Zero)
{
throw new Exception();
}
}
catch (Exception)
{
throw new Exception("nfc_open() failed.");
}
return new NFCDevice(devicePointer);
}
public string Version()
{
var ptr = Functions.nfc_version();
return Marshal.PtrToStringAuto(ptr);
}
public virtual void Dispose()
{
Functions.nfc_exit(contextPointer);
}
}
}