Calling a Method object

Is there any way to do this?

julia> m = @which sin(1)
sin(x::Real) in Base.Math at special/trig.jl:53

julia> m(20)
ERROR: MethodError: objects of type Method are not callable
Stacktrace:
 [1] top-level scope at REPL[5]:1

I don’t mind using internals if necessary…

julia> args = Any[2.0];

julia> m = @which f(args...);

julia> mi = Core.Compiler.specialize_method(m, Tuple{typeof(f), (typeof.(args))...}, Core.svec())
MethodInstance for sin(::Float64)

julia> function jl_invoke(f, args, mi)
            ccall(:jl_invoke, Any, (Any, Ptr{Any}, Cuint, Any), f, args, length(args), mi)
       end;

julia> jl_invoke(f, args, mi)
0.9092974268256817)

julia> f(args...)
0.9092974268256817

is one way, not sure it is the best one (both in terms of correctness and performance) but might get you started. Also look at jl_lookup_generic, and jl_apply_generic.

2 Likes