Skip to content

Instantly share code, notes, and snippets.

@bermanmaxim
Last active August 29, 2015 14:24
Show Gist options
  • Save bermanmaxim/65a568b6db9093d92f3d to your computer and use it in GitHub Desktop.
Save bermanmaxim/65a568b6db9093d92f3d to your computer and use it in GitHub Desktop.
using PyCall
import Base.next
import Base: sigatomic_begin, sigatomic_end
#overwrite 'next' definition in PyCall
function next(po::PyObject, s)
sigatomic_begin()
try
nxt = PyObject(ccall((PyCall.@pysym :PyIter_Next), PyPtr, (PyPtr,), s[2]))
return (s[1], (nxt, s[2])) # No conversion to PyAny
finally
sigatomic_end()
end
end
function jl_Function_call_raw(self_::PyPtr, args_::PyPtr, kw_::PyPtr)
ret_ = convert(PyPtr, C_NULL)
println("Custom wrapper used")
args = PyObject(args_)
try
f = PyCall.unsafe_pyjlwrap_to_objref(self_)::Function
if kw_ == C_NULL
ret = PyObject(f(args...))
else
kw = PyDict{Symbol,PyObject}(PyObject(kw_))
kwargs = [ (k,v) for (k,v) in kw ]
ret = PyObject(f(args...; kwargs...))
end
ret_ = ret.o
ret.o = convert(PyPtr, C_NULL) # don't decref
catch e
pyraise(e)
finally
args.o = convert(PyPtr, C_NULL) # don't decref
end
return ret_::PyPtr
end
global const jl_Function_call_ptr_raw =
cfunction(jl_Function_call_raw, PyPtr, (PyPtr,PyPtr,PyPtr))
global const jl_FunctionType_raw = PyCall.pyjlwrap_type("PyCall.jl_Function_raw",
t -> t.tp_call =
jl_Function_call_ptr_raw);
function pycallback_raw(f::Function)
PyCall.pyjlwrap_new(jl_FunctionType_raw, f)
end
PyObject(f::Function) = pycallback_raw(f) # overwrite PyCall's conversion Function -> PyObject
a = pycall(pyimport("numpy")["array"], PyArray, [0])
function incr(a::PyObject)
a = convert(PyArray, a)
a[1] += 1
a
end
pyeval("incr(a)", a = a, incr=incr);
println(a) # shows [1] :)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment