Julia call c struct function

,

I need to interface the C language update_leaf function with Julia. But the current script has memory error.

// leaf.c 
// gcc -shared -fPIC -o leaf.o leaf.c
#include <stdio.h>

/** second solution */
typedef struct {
    int x;
    double y;
    double z[2];
} Leaf;

#define LEAF(...) ((Leaf){.x = 0, .y = 0, .z = {0.0, 1.0}, ##__VA_ARGS__})

void init_leaf_obj(Leaf obj[]) {
  obj->x = 1;
  obj->y = 2;

  obj->z[0] = 1;
  obj->z[1] = 2;
} 

Leaf init_leaf(int a) {
    Leaf x;
    init_leaf_obj(&x);
    return x;
}

void update_leaf(Leaf obj[], double val) {
    // Leaf x;
    // init_leaf_obj(&x);
    obj->y = val;
    // obj->z[0] = val;
    // obj->z[1] = val;
    // return x;
}

int main() {
  printf("hello");  
  Leaf x = init_leaf(1);

  return 1;
}
using Libdl
# include("test/Soil.jl")
# p = Soil()

mutable struct Leaf_1
  x::Cint
  y::Cdouble
  z::NTuple{2,Cdouble}
end

mutable struct Leaf
  x::Cint
  y::Cdouble
  z::Ptr{Cdouble}
end

libpath = "leaf_1.o"
run(`gcc -shared -fPIC -o $libpath leaf.c`)


leaf = ccall((:init_leaf, libpath),
  Leaf_1, (Cint,), Cint(1))

x = [leaf]
ccall((:update_leaf, libpath),
  Leaf,
  (Ptr{Leaf}, Cdouble),
  x, Cdouble(99.0))

leaf

Any idea how to solve?

The code you pasted works as is but that is not the same code as in your screenshot. I removed some unsed things, but this works:

// leaf.c
#include <stdio.h>

typedef struct {
    int x;
    double y;
    double z[2];
} Leaf;

void init_leaf_obj(Leaf obj[]) {
  obj->x = 1;
  obj->y = 2;
  obj->z[0] = 1;
  obj->z[1] = 2;
}

Leaf init_leaf(int a) {
    Leaf x;
    init_leaf_obj(&x);
    return x;
}

void update_leaf(Leaf obj[], double val) {
    obj->y = val;
}
# leaf.jl
using Libdl

libpath = abspath("leaf.so")
run(`gcc -shared -fPIC -o $libpath leaf.c`)

mutable struct Leaf
  x::Cint
  y::Cdouble
  z::NTuple{2,Cdouble}
end

leaf = ccall((:init_leaf, libpath), Leaf, (Cint,), 1)

ccall((:update_leaf, libpath), Cvoid, (Ptr{Leaf}, Cdouble), Ref(leaf), 99.0)
1 Like

Thank you @fredrikekre. Thank for your solution.
In my screenshot, it really not work. But now it is different. It is little weird.