forked from JuliaInterop/RCall.jl
/
callback.jl
166 lines (139 loc) · 4.45 KB
/
callback.jl
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
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
"""
Register a function pointer as an R NativeSymbol. We technically are supposed to use
R_registerRoutines. Starting from R 3.4, `R_MakeExternalPtrFn` is a part of R API in R 3.4.
It is probably safe to such to make the external pointer.
"""
function makeNativeSymbolRef(fptr::Ptr{Void})
# mirror Rf_MakeNativeSymbolRef of Rdynload.c
rexfn = ccall((:R_MakeExternalPtrFn,libR), Ptr{ExtPtrSxp},
(Ptr{Void}, Ptr{Void}, Ptr{Void}),
fptr, sexp(Symbol("native symbol")), sexp(Const.NilValue))
setattrib!(rexfn, Const.ClassSymbol, sexp("NativeSymbol"))
preserve(rexfn)
rexfn
end
"Create an Ptr{ExtPtrSxp} object"
makeExternalPtr(ptr::Ptr{Void}, tag=Const.NilValue, prot=Const.NilValue) =
ccall((:R_MakeExternalPtr,libR), Ptr{ExtPtrSxp},
(Ptr{Void}, Ptr{UnknownSxp}, Ptr{UnknownSxp}),
ptr, sexp(tag), sexp(prot))
"""
The function called by R .External for Julia callbacks.
It receives a `Ptr{ListSxp}` containing
- a pointer to the function itself (`Ptr{ExtPtrSxp}`)
- a pointer to the Julia function (`Ptr{ExtPtrSxp}`)
- any arguments (as `Ptr{S<:Sxp}`)
"""
function julia_extptr_callback(p::Ptr{ListSxp})
try
l = cdr(p) # skip callback pointer
# julia function pointer
f_sxp = car(l)::Ptr{ExtPtrSxp}
f_sxprec = unsafe_load(f_sxp)
f = unsafe_pointer_to_objref(f_sxprec.ptr)
l = cdr(l)
# # extract arguments
args = Any[]
kwargs = Any[]
for (k,a) in l
# TODO: provide a mechanism for users to specify their own
# conversion routines
if k == sexp(Const.NilValue)
push!(args,rcopy(a))
else
push!(kwargs,(rcopy(Symbol,k),rcopy(a)))
end
end
# call function
y = f(args...;kwargs...)
# return appropriate sexp
return p = convert(Ptr{UnknownSxp},sexp(y))::Ptr{UnknownSxp}
catch e
ccall((:Rf_error,libR),Ptr{Void},(Ptr{Cchar},),string(e))
return convert(Ptr{UnknownSxp},sexp(Const.NilValue))::Ptr{UnknownSxp}
end
end
"""
Julia types (typically functions) which are wrapped in `Ptr{ExtPtrSxp}` are
stored here to prevent garbage collection by Julia.
"""
const jtypExtPtrs = Dict{Ptr{ExtPtrSxp}, Any}()
"""
Called by the R finalizer.
"""
function decref_extptr(p::Ptr{ExtPtrSxp})
delete!(jtypExtPtrs, p)
return nothing
end
"""
Register finalizer to be called by the R GC.
"""
function registerCFinalizerEx(s::Ptr{ExtPtrSxp})
protect(s)
decref_extptr_ptr = cfunction(decref_extptr,Void,(Ptr{ExtPtrSxp},))
ccall((:R_RegisterCFinalizerEx,libR),Void,
(Ptr{ExtPtrSxp}, Ptr{Void}, Cint),
s,decref_extptr_ptr,0)
unprotect(1)
end
const juliaCallback = RObject{ExtPtrSxp}()
function setup_callbacks()
julia_extptr_callback_ptr = cfunction(julia_extptr_callback,Ptr{UnknownSxp},(Ptr{ListSxp},))
juliaCallback.p = makeNativeSymbolRef(julia_extptr_callback_ptr)
end
"""
Wrap a Julia object an a R `Ptr{ExtPtrSxp}`.
We store the pointer and the object in a const Dict to prevent it being
removed by the Julia GC.
"""
function sexp(::Type{ExtPtrSxp}, j)
jptr = pointer_from_objref(j)
s = makeExternalPtr(jptr)
jtypExtPtrs[s] = j
registerCFinalizerEx(s)
s
end
"""
Wrap a callable Julia object `f` an a R `ClosSxpPtr`.
Constructs the following R code
function(...) .External(juliaCallback, fExPtr, ...)
"""
function sexp(::Type{ClosSxp}, f)
fptr = protect(sexp(ExtPtrSxp,f))
body = protect(rlang_p(Symbol(".External"),
juliaCallback,
fptr,
Const.DotsSymbol))
local clos
try
lang = rlang_p(:function, sexp_arglist_dots(), body)
clos = reval_p(lang)
finally
unprotect(2)
end
clos
end
"""
Create an argument list for an R function call, with a varargs "dots" at the end.
"""
function sexp_arglist_dots(args...;kwargs...)
rarglist = protect(allocList(length(args)+length(kwargs)+1))
try
rr = rarglist
for var in args
settag!(rr, sexp(var))
setcar!(rr, Const.MissingArg)
rr = cdr(rr)
end
for (var,val) in kwargs
settag!(rr, sexp(var))
setcar!(rr, sexp(val))
rr = cdr(rr)
end
settag!(rr, Const.DotsSymbol)
setcar!(rr, Const.MissingArg)
finally
unprotect(1)
end
rarglist
end