Cfunction pointer back to Function?


#1
julia> foo() = Cint(1)
foo (generic function with 1 method)

julia> ptr = cfunction(foo, Cint, Tuple{})
Ptr{Nothing} @0x00007f5dacc48510

Is it possible to derive foo from ptr?


#2
julia> foo() = Cint(1);

julia> ptr = cfunction(foo, Cint, Tuple{});

julia> _foo = unsafe_wrap(Array, reinterpret(Ptr{typeof(foo)}, ptr), (), false)[];

julia> _foo === foo
true

julia> foo()
1

julia> _foo()
1

#3

unsafe_wrap(Array, reinterpret(Ptr{typeof(foo)}, ptr), (), false)[] uses foo, and I’m curious if it can be done without it. Sorry if I was unclear.


#4

How about directly call it by ccall, but in this way, foo's signature info is still needed :

julia> foo() = Cint(1)
foo (generic function with 1 method)

julia> ptr = cfunction(foo, Cint, Tuple{})
Ptr{Void} @0x0000000111712e30

julia> _foo() = ccall(ptr, Cint, ())
_foo (generic function with 1 method)

#5

The use case I had in mind was for a C library’s callback setter. E.g. void* SetCallback(void* funcPtr) sets a new callback function, and returns the previous callback function. I was curious if that returned function pointer could be changed back into a Julia Function without knowing anything more about it.


#6

No you can’t do that. Only with debug info maybe but that shouldn’t be used in normal code.

This is only a complicated way to spell typeof(foo).instance. The ptr is not used AT ALL.


#7

Each time you call SetCallback from Julia, you could store the Function object in a dictionary keyed by the cfunction, e.g. mydict[mycfunction] = myfunction. Then the next time you call SetCallback you could look up the Function in your dictionary if you want.