-
Notifications
You must be signed in to change notification settings - Fork 78
Expand file tree
/
Copy pathCallbackEx.cs
More file actions
84 lines (67 loc) · 2.65 KB
/
CallbackEx.cs
File metadata and controls
84 lines (67 loc) · 2.65 KB
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
77
78
79
80
81
82
83
84
// Copyright (c) libplctag.NET contributors
// https://github.com/libplctag/libplctag.NET
//
// This Source Code Form is subject to the terms of the Mozilla Public
// License, v. 2.0. If a copy of the MPL was not distributed with this
// file, You can obtain one at https://mozilla.org/MPL/2.0/.
using System;
using System.Runtime.InteropServices;
using System.Threading;
using libplctag.NativeImport;
namespace NativeImport_Examples
{
public struct MyUserDataClass
{
public int Value;
public MyUserDataClass()
{
Value = 1234;
}
}
class CallbackEx
{
public static void Run()
{
// Create the tag handle
var tagHandle = plctag.plc_tag_create("protocol=ab_eip&gateway=127.0.0.1&path=1,0&plc=LGX&elem_size=4&elem_count=1&name=MyTag[0]", 1000);
var statusBeforeRead = plctag.plc_tag_status(tagHandle);
if (statusBeforeRead != 0)
{
Console.WriteLine($"Something went wrong {statusBeforeRead}");
}
while (plctag.plc_tag_status(tagHandle) == 1)
{
Thread.Sleep(100);
}
// Create some user data and pin it in memory
var myUserData = new MyUserDataClass();
var myUserDataPtr = GCHandle.Alloc(myUserData, GCHandleType.Pinned);
// ... so that we can pass it to our callback,
var myCallback = new plctag.callback_func_ex(MyCallback);
var statusAfterRegistration = plctag.plc_tag_register_callback_ex(tagHandle, myCallback, (IntPtr)myUserDataPtr);
if (statusAfterRegistration != 0)
{
Console.WriteLine($"Something went wrong {statusAfterRegistration}");
}
plctag.plc_tag_read(tagHandle, 1000);
while (plctag.plc_tag_status(tagHandle) == 1)
{
Thread.Sleep(100);
}
var statusAfterRead = plctag.plc_tag_status(tagHandle);
if (statusAfterRead != 0)
{
Console.WriteLine($"Something went wrong {statusAfterRead}");
}
plctag.plc_tag_destroy(tagHandle);
myUserDataPtr.Free();
}
public static void MyCallback(int tag_id, int event_id, int status, IntPtr userDataPtr)
{
// ... and retrieve it later
var gcHandle = GCHandle.FromIntPtr(userDataPtr);
var userData = (MyUserDataClass)gcHandle.Target;
Console.WriteLine($"Tag Id: {tag_id} Event Id: {event_id} Status: {status} User Data: {userData.Value}");
}
}
}