Skip to content

Instantly share code, notes, and snippets.

@ahojukka5
Last active February 21, 2021 15:51
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save ahojukka5/ab3a198ca25ce55e4f6947c217e0293f to your computer and use it in GitHub Desktop.
Save ahojukka5/ab3a198ca25ce55e4f6947c217e0293f to your computer and use it in GitHub Desktop.
ccall julia
#include <stdlib.h>
#include <stdio.h>
// gcc -shared -o vector2.so vector2.c
typedef struct Vec {
long int length;
double* data;
} Vec;
Vec new_vector(long int length) {
Vec v;
v.length = length;
v.data = malloc(sizeof(double) * length);
return v;
}
void set_vector_data(Vec *v, long int i, double val) {
v->data[i] = val;
}
double get_vector_data(Vec *v, long int i) {
return v->data[i];
}
int main(int argc, char* argv[]) {
Vec vec = new_vector(3);
Vec* vecp = &vec;
set_vector_data(vecp, 0, 1.5);
set_vector_data(vecp, 1, 2.5);
set_vector_data(vecp, 2, 3.5);
printf("v[0] = %f\n", get_vector_data(vecp, 0));
printf("v[1] = %f\n", get_vector_data(vecp, 1));
printf("v[2] = %f\n", get_vector_data(vecp, 2));
}
const lib = "./vector2.so"
mutable struct Vec
length :: Int
data :: Ptr{Cdouble}
end
function Vector(n::Int)
return ccall((:new_vector, lib), Vec, (Cint, ), n)
end
function set_vector_data(v, i::Int, val::Float64)
ccall((:set_vector_data, lib), Cvoid, (Ptr{Vec}, Clong, Cdouble), Ref(v), i, val)
end
function get_vector_data(v::Vec, i::Int)
return ccall((:get_vector_data, lib), Cdouble, (Ptr{Vec}, Cint, ), Ref(v), i)
end
function test()
println("test 1 start")
v = Vector(3)
println(v)
set_vector_data(v, 0, 1.5)
set_vector_data(v, 1, 2.5)
set_vector_data(v, 2, 3.5)
for i=1:3
println("unsafe_load, v.data[$i] = ", unsafe_load(v.data, i))
end
data = unsafe_wrap(Array, v.data, 3; own = false)
println("data = ", data)
data[2] += 5
for i=0:2
println("v[$i] = $(get_vector_data(v, i))")
end
println("test 1 end")
end
function test2()
println("test 2 start")
data = [1.5, 2.5, 3.5]
v = Vec(3, pointer(data))
println(v)
data[2] += 5
println("data = ", data)
for i=0:2
println("v[$i] = $(get_vector_data(v, i))")
end
println("test 2 end")
end
test()
test2()
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment