I have succesfully tried out the PackageCompiler library + Python Ctypes example from
Sadly the example is extremely simple and does not show how to pass parameters, especially arrays from python.
I would be thankful for any working (and idiomatic) snippet passing a numpy array to a PackageCompiler-generated Julia library , but i will also post what I tried so far.
(My version prints wrong data when i request the array size.)
Since i was experimenting with the StaticCompiler first, i know two possibilities how it can be done there
a) with separate pointer and length, shown here:
Successful Static Compilation of Julia Code for use in Production
b) using the same info, but packed into a struct and then passing a reference to the struct as shown here:
GitHub - brenhinkeller/StaticTools.jl: Enabling StaticCompiler.jl-based compilation of (some) Julia code to standalone native binaries by avoiding GC allocations and llvmcall-ing all the things!
I found version (b) to be a bit more organized and thus decided to try this. Here are my code snippets:
Julia - tries to only output the size field. So actually this only tests struct passing and not even the actual array functionality. Probaly there is also some stuff missing to get true array functionality (getindex, setindex etc)
struct MallocArray{T,N} <: DenseArray{T,N}
pointer::Ptr{T}
length::Int
size::NTuple{N, Int}
end
const MallocMatrix{T} = MallocArray{T,2}
Base.@ccallable function func1( a::RefValue{MallocMatrix{Float64}},
b::RefValue{MallocMatrix{Float64}}) :: Cvoid
println(a[].size)
println(b[].size)
end
Python
class MallocMatrix(ct.Structure):
_fields_ = [("pointer", ct.c_void_p),
("length", ct.c_int64),
("s1", ct.c_int64),
("s2", ct.c_int64)]
def getMatrixptr(A):
ptr = A.ctypes.data_as(ct.c_void_p)
a = MallocMatrix(ptr, ct.c_int64(A.size), ct.c_int64(A.shape[1]), ct.c_int64(A.shape[0]))
return ct.byref(a)
a = np.zeros((7,2))
b = np.zeros((10,2))
print("func1")
lib.func1(getMatrixptr(a),getMatrixptr(b))
Output (should be 7,2 and 10,2)
func1
(140732223482816, 139903138553959)
(8, 1)