JuliaPy / PyCall.jl

Package to call Python functions from the Julia language
MIT License
1.46k stars 187 forks source link

Is there a way to pass a Python ctypes pointer to Julia then use it in a ccall? #868

Closed marius311 closed 3 years ago

marius311 commented 3 years ago

Basically I have some Python code which uses ctypes to wrap some Fortran structs, and on the Python side I can do a byref(some_wrapped_object) to get a pointer which I can then pass as an argument to some Fortran calls. Is there a way to pass the pointer to Julia then use that in a ccall instead? The object looks like:

In [1]: byref(some_wrapped_object)                                                                                                                  
Out[1]: <cparam 'P' (0x55a0ec981d80)>
stevengj commented 3 years ago

Use ctypes.cast to get a c_void_p, which PyCall knows to convert to a Julia pointer. For example:

julia> ctypes = pyimport("ctypes");

julia> o = ctypes.byref(pycall(ctypes.c_int, PyObject, 3))
PyObject <cparam 'P' (0x7fa9929a3910)>

julia> ctypes.cast(o, ctypes.c_void_p)
Ptr{Nothing} @0x00007fa9929a3910
marius311 commented 3 years ago

Beautiful, thank you!