-
Notifications
You must be signed in to change notification settings - Fork 43
/
Copy pathProgram.cs
83 lines (73 loc) · 2.97 KB
/
Program.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
77
78
79
80
81
82
83
using DynamicInterop;
using RDotNet;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Runtime.InteropServices;
using System.Text;
using System.Threading.Tasks;
namespace CallbackFunctions
{
/// <summary>
/// A sample code that was written to answer the question http://rdotnet.codeplex.com/discussions/646729
/// </summary>
class Program
{
public static void Main(string[] args)
{
REngine.SetEnvironmentVariables();
REngine engine = REngine.GetInstance();
rdotnet_discussions_646729(engine);
// you should always dispose of the REngine properly.
// After disposing of the engine, you cannot reinitialize nor reuse it
engine.Dispose();
}
[UnmanagedFunctionPointer(CallingConvention.Cdecl)]
internal delegate void ProgressNotificationHandler([In] [MarshalAs(UnmanagedType.LPStr)] string buffer, double percentage);
private class CallBackHandlers
{
public void ProcessProgress(string buffer, double percentage)
{
Console.WriteLine(string.Format("C# progress handler: at {0}% - {1}", percentage, buffer));
}
}
[StructLayout(LayoutKind.Sequential)]
class TestCallback
{
[MarshalAs(UnmanagedType.FunctionPtr)]
public ProgressNotificationHandler MyHandler;
}
[UnmanagedFunctionPointer(CallingConvention.Cdecl)]
internal delegate void register_default_progress_handler(ProgressNotificationHandler delegatePtr);
static void rdotnet_discussions_646729(REngine engine)
{
var setup = @"library(rdotnetsamples)
rdotnetsamples::register_default_progress_handler()
";
engine.Evaluate(setup);
var myRFunction = @"
my_r_calculation <- function()
{
for (i in seq(0, 100, by=20)) {
rdotnetsamples::broadcast_progress_update(paste0('Some Update Message for ', i), i);
}
}
";
engine.Evaluate(myRFunction);
engine.Evaluate("my_r_calculation()");
var unixDllPath = engine.Evaluate("getLoadedDLLs()$rdotnetsamples[['path']]").AsCharacter()[0];
var dllPath = unixDllPath.Replace("/", "\\");
var dll = new DynamicInterop.UnmanagedDll(dllPath);
TestCallback cback = new TestCallback();
CallBackHandlers cbh = new CallBackHandlers();
cback.MyHandler = cbh.ProcessProgress;
string cFunctionRegisterCallback = "register_progress_handler";
register_default_progress_handler registerHandlerFun = dll.GetFunction<register_default_progress_handler>(cFunctionRegisterCallback);
registerHandlerFun(cback.MyHandler);
Console.WriteLine();
Console.WriteLine("After registering the callback with a function pointer to a C# function:");
Console.WriteLine();
engine.Evaluate("my_r_calculation()");
}
}
}