@cfunction within function, scoping problem

it seems that the macro @cfunction work only with function defined in global scope.
Used within a function like

function get_ptr(f::Function)
    integrand_c = @cfunction( $f,Cdouble,(Ptr{Cdouble},Ptr{Cdouble},Ptr{Cdouble}))
    ptr = Base.unsafe_convert(Ptr{Cvoid}, Base.cconvert(Ptr{Cvoid}, integrand_c))
    return ptr

will trigger f not defined.
Changing f to $f seems to solve the problem, but then when using ccall my program hangs.
Is there a proper way to use @cfunction on a julia callable within a function?


julia/ccall.jl at master · JuliaLang/julia · GitHub has tons of examples.

thanks for the quick answer.
But as far as i can see from the example , the only way to do what i would like to do, is to encapsulate the function parameter into local closure ( using $f) which in turn do not work in my case.
The C function called via ccall hangs…
Using the globally defined callable function works perfectly.
So the call to

  • @cfunction ( callable ... ) and
  • @cfunction($callable ... )

do not behave the same

Why? That might be the root cause, but you just make the conclusion without providing any diagnostic info.

I don’t know why.
The C function called via ccall is also multi-threaded. Using callable define on the global scope
works perfectly, but using @cfunction($callable...) inside a function, the C called function hangs in a deadlock, probably a race condition.
Is it allowed to call multithreaded C function with ccall. Or it there something one should be aware of?
Which diagnostic info should i provide?

An MWE that can reproduce the problem.

For now i have no MWE, but i could try to make one…

ccall does have some problems if the C library calls the callback function in a different thread(see Support call-back functions? · Issue #56 · JuliaAudio/PortAudio.jl · GitHub, Calling C and Fortran Code · The Julia Language), but it looks like your case is a little bit different.

the called C function does not segfault because of incomplete thread safety support but end up in a deadlock … this is indeed a bit different.
I can try to figure out where this exaclty happen …

From what I understand, you do currently to to call into Julia from different C-threads, @dbertini, correct?

well, i do the following for the C interface:
I translate a native user-defined Julia function via @cfunction(callable)
After that an optimize() function is called that will use the converted C function
from @cfunction() macro and execute internally ccall.
When callable is defined on global scope and i convert the user-defined function
with @cfunction before calling optimize() everything works fine.
When i pass the native user function as parameter optimize(f::Function) and use then the macro
with the closure @cfunction( $f) the ccall hangs in a deadlock.