Dear Julia developers,
It’s almost a week I’m trying to call a custom C (or C++) function in Julia.
In particular what I want is to call a C function I wrote which takes some matrices as arguments and modify one of these. I still didn’t understand if I need to return it or since I give it a pointer it should modify it. Btw, I’m not able to do this task and I’ve tried everything. Your help is REALLY appreciated.
In detail, the function I wrote in C is:
ccode.c
#include <math.h>
#include <string.h>
//#include <stdio.h>
void prob( double **p, double **a, double **b, int na, int nb) {
for (int i=0; i<na; i++){
double pr=a[i][0];
for (int n=0; n<nb; n++){
double pr_n=pr;
for (size_t l=0; l < sizeof(b[n]); l++){
pr_n=pr_n+b[n][l]*a[i][l+1];
};
pr_n=1/(1+exp(-pr_n));
p[i][n]=pr_n;
};
};
};
then I run with no errors:
>g++ -o ccode.so -lm ccode.c -fPIC -shared -Wall
in my working directory and in Julia I wrote:
ccode.jl
p=zeros(Float64,1000,3000)
a=rand(Float64,100,1000)
b=rand(Float64,3000,100)
Base.cconvert(::Type{Ptr{Ptr{Cdouble}}},matrix::Matrix{Float64})=Ref{Ptr{Cdouble}}([Ref(matrix,i) for i=1:size(matrix,1):length(matrix)])
function tryccall(p,a,b,nItems,nStud)
#here some tries to convert the matrix in 2d array of pointers:
#p = [Ref(p,i) for i=1:size(p,1):length(p)]
#a = [Ref(a,i) for i=1:size(a,1):length(a)]
#b = [Ref(b,i) for i=1:size(b,1):length(b)]
#p=pointer(p)
#a=pointer(a)
#b=pointer(b)
#p=Base.cconvert(Ptr{Ptr{Cdouble}},p)
#b=Base.cconvert(Ptr{Ptr{Cdouble}},b)
#a=Base.cconvert(Ptr{Ptr{Cdouble}},a)
ccall(("prob", "$pwd()//ccode"), Cvoid, (Ptr{Ptr{Cdouble}}, Ptr{Ptr{Cdouble}}, Ptr{Ptr{Cdouble}}, Cint, Cint), p, a, b, 1000,3000)
#eval(:(ccall((:prob, "$pwd()//ccode"), Cvoid, (Ptr{Ptr{Cdouble}}, Ptr{Ptr{Cdouble}}, Ptr{Ptr{Cdouble}}, Cint, Cint), p, pars, latents, 1000,3000)))
end
But I cannot load the library ccode.so. I also tried to add it with Libdl.opendl but it still doesn’t work.
Also adding the working directory to the LOAD_PATH path doesn’t work.
also I get the following error:
TypeError: in ccall: first argument not a pointer or valid constant expression, expected Ptr, got Tuple{String,String}
I tried to use a symbol but it’s still the same.
What can I do?
Thank you in advance
Giada