Skip to content

Commit

Permalink
Allow SafeCFunction to work on a closure
Browse files Browse the repository at this point in the history
  • Loading branch information
barche committed Jan 19, 2021
1 parent 44f826b commit 588e124
Show file tree
Hide file tree
Showing 2 changed files with 18 additions and 1 deletion.
13 changes: 12 additions & 1 deletion src/CxxWrap.jl
Expand Up @@ -759,14 +759,25 @@ macro initcxx()
return :(initialize_julia_module($__module__))
end

# This struct is mirrored in C++, with always a pointer in the first field
struct SafeCFunction
fptr::Ptr{Cvoid}
return_type::Type
argtypes::Array{Type,1}
end

# Helper struct that can store a Base.CFunction
struct _SafeCFunction
fptr::Union{Ptr{Cvoid},Base.CFunction}
return_type::Type
argtypes::Array{Type,1}
end

Base.convert(::Type{SafeCFunction}, f::_SafeCFunction) = SafeCFunction(Base.unsafe_convert(Ptr{Cvoid}, f.fptr), f.return_type, f.argtypes)
map_julia_arg_type(x::Type{SafeCFunction}) = _SafeCFunction

macro safe_cfunction(f, rt, args)
return esc(:($(@__MODULE__).SafeCFunction(@cfunction($f, $rt, $args), $rt, [$(args.args...)])))
return esc(:($(@__MODULE__)._SafeCFunction(@cfunction($f, $rt, $args), $rt, [$(args.args...)])))
end

isnull(x::CxxBaseRef) = (x.cpp_object == C_NULL)
Expand Down
6 changes: 6 additions & 0 deletions test/functions.jl
Expand Up @@ -112,6 +112,12 @@ c_func = @safe_cfunction(testf, Float64, (Float64,Float64))
CppTestFunctions.test_safe_cfunction(c_func)
CppTestFunctions.test_safe_cfunction2(c_func)

function local_testf()
testf_private(x,y) = x + y
return @safe_cfunction($testf_private, Float64, (Float64,Float64))
end
CppTestFunctions.test_safe_cfunction(local_testf())

Base.show(io::IO, x::CppTestFunctions.BoxedNumber) = show(io, CppTestFunctions.getnumber(x))

let boxed_num_val = Ref{Int32}(0)
Expand Down

0 comments on commit 588e124

Please sign in to comment.