Lately, I’ve managed to pass a BigInt to C and back (Passing GMP variables from C(++) to Julia - #10 by Questioner). Now suppose I want to generate Fibonacci numbers in C and pass them to Julia. I thought I just take the analogous code for arrays
#include<gmp.h>
void test(mpz_t* var[]) {
mpz_init_set_ui(*var[1], 2);
}
but upon calling it
@ccall "./art.so".test(x::Ptr{Ref{BigInt}})::Cvoid
where x was
x
2-element Vector{Ref{BigInt}}:
Base.RefValue{BigInt}(3)
Base.RefValue{BigInt}(3)
it ran, but crashed upon typing “x” and hitting enter, producing a lengthy error message.
I’d be grateful for any input on how to solve this problem.
I’ve finally found a workaround: I’m first creating an array in Julia
grr = Array{BigInt}(undef, 2)
then I save pointers to the elements of that array into a different array
arr = Array{Ptr{Nothing}}(undef, 2)
for j in 1:2
arr[j] = pointer_from_objref(grr[j])
end
This last array is what I pass to C:
@ccall "./gmptest.so".modify2(arr::Ref{Ptr{Nothing}})::Cvoid
C then operates on arr
, like in the following code:
void modify2(mpz_t* arr[]) {
mpz_set_ui(*arr[1], 10);
}
Can’t you just pass grr
to modify2
directly? i.e.
@ccall "./gmptest.so".modify2(grr::Ptr{BigInt})::Cvoid
since a Vector{BigInt}
is stored under the hood as an array of pointers to BigInt
objects (which aren’t stored inline since they are mutable structs), and BigInt
objects are laid out identically to mpz_t
(so that they can be passed by reference to GMP functions).