Skip to content

Instantly share code, notes, and snippets.

@jfsantos
Last active October 16, 2018 13:42
Show Gist options
  • Select an option

  • Save jfsantos/9136352 to your computer and use it in GitHub Desktop.

Select an option

Save jfsantos/9136352 to your computer and use it in GitHub Desktop.
Passing structures and arrays back and forth in Julia with ccall
immutable Cdvec
val::Ptr{Cdouble}
len::Clong
end
a = [1.0, 2.0, 3.0]
b = [3.1, 4.2, 7.3]
Ca = Cdvec(pointer(a), length(a))
Cb = Cdvec(pointer(b), length(b))
Cc = Ptr{Cdvec}[C_NULL]
push!(DL_LOAD_PATH, ".")
x = unsafe_load(ccall((:get_dvec, "test_ccall_lib"), Ptr{Cdvec}, ()))
l = ccall((:get_dvec_ptr, "test_ccall_lib"), Cint, (Ptr{Cdvec},), Cc)
err = ccall((:dvec_sum, "test_ccall_lib"), Int32, (Ptr{Cdvec}, Ptr{Cdvec}, Ptr{Cdvec}), &Ca, &Cb, Cc)
c = unsafe_load(Cc[1])
if err != 0
print("Error: vectors have different length")
else
for i = 1:(c.len)
println(unsafe_load(c.val, i))
end
end
#include <stdlib.h>
#include <stdio.h>
typedef struct dvec {
double* val;
long len;
} dvec;
typedef struct lvec {
long* val;
long len;
} lvec;
int dvec_sum(dvec* a, dvec* b, dvec** c) {
printf("Original c address: %p\n", c);
if (a->len != b->len) {
return -1; // different lengths, can't sum
} else {
int l = a->len;
dvec *cc = (dvec*)malloc(sizeof(dvec));
cc->val = (double*) malloc(sizeof(double)*l);
cc->len = l;
for(int i = 0; i < l; i++) {
cc->val[i] = a->val[i] + b->val[i];
printf("%f\n", cc->val[i]);
}
*c = cc;
printf("Return val address: %p\n", c);
return 0;
}
}
dvec* get_dvec() {
dvec* c = (dvec*)malloc(sizeof(dvec));
c->val = (double*) malloc(sizeof(double)*4);
c->val[0] = 1.0;
c->val[1] = 2.0;
c->val[2] = 3.0;
c->val[3] = 4.0;
c->len = 4;
return c;
}
int get_dvec_ptr(dvec** cc) {
dvec *c = (dvec*)malloc(sizeof(dvec));
c->val = (double*) malloc(sizeof(double)*4);
c->val[0] = 1.0;
c->val[1] = 2.0;
c->val[2] = 3.0;
c->val[3] = 4.0;
c->len = 4;
*cc = c;
return c->len;
}
@jfsantos
Copy link
Copy Markdown
Author

This is the output:

julia> require("test_ccall.jl")
4.100000
6.200000
10.300000
ERROR: type Array has no field len
 in anonymous at no file:20
 in reload_path at loading.jl:144
 in _require at loading.jl:59
 in require at loading.jl:43
while loading /home/jfsantos/Projects/test_ccall/test_ccall.jl, in expression starting on line 17

julia> Cc
1-element Array{Ptr{T},1}:
 Ptr{Void} @0x0000000000000000

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment