# Loading arrays from C calls

**URL:** <https://discourse.julialang.org/t/loading-arrays-from-c-calls/59781>\
**Category:** Internals & Design\
**Created:** [April 22, 2021, 6:53am UTC](https://discourse.julialang.org/t/loading-arrays-from-c-calls/59781 "2021-04-22T06:53:33Z")\
**Posts on this page:** 11\
**Page:** 1

<div class="post-metadata">

**Author:** ![Anton\_Hinneck](https://sea2.discourse-cdn.com/julialang/user_avatar/discourse.julialang.org/anton_hinneck/32/22716_2.png) [@Anton\_Hinneck](https://discourse.julialang.org/u/Anton_Hinneck)\
**Post date:** [April 22, 2021, 6:53am UTC](https://discourse.julialang.org/t/loading-arrays-from-c-calls/59781/1 "2021-04-22T06:53:33Z")

</div>

Hi,  
I need to work with packages that wrap a C-callable library (\*.so). Code that worked previously now causes segfaults when trying to load arrays. As a test, I compiled a small library called retArray.so containing the following code: (the function **getRandom()** I is from [here](https://coderoad.ru/31366158/%D0%A7%D1%82%D0%BE-%D1%8D%D1%82%D0%BE%D1%82-%D0%BC%D0%B0%D1%81%D1%81%D0%B8%D0%B2-%D0%BE%D0%BF%D1%80%D0%B5%D0%B4%D0%B5%D0%BB%D1%8F%D0%B5%D1%82%D1%81%D1%8F-%D0%BA%D0%B0%D0%BA-%D1%81%D1%82%D0%B0%D1%82%D0%B8%D1%87%D0%B5%D1%81%D0%BA%D0%B8%D0%B9-%D0%B0-%D0%BD%D0%B5-%D0%B3%D0%BB%D0%BE%D0%B1%D0%B0%D0%BB%D1%8C%D0%BD%D1%8B%D0%B9))

```julia
#include <stdio.h>
#include <stdlib.h>
#include <time.h>

/* function to generate and return random numbers */
int * getRandom( ) {

   static int r[10];
   int i;

   /* set the seed */
   srand( (unsigned)time( NULL ) );
  
   for ( i = 0; i < 10; ++i) {
      r[i] = rand();
      printf( "r[%d] = %d\n", i, r[i]);
   }

   return r;
}

```

I then use ccall to use the function getRandom like so in Julia:

```julia
julia> retRndArr() = ccall(("getRandom", "/home/anton_hinneck/projects/ccall_test/retArray.so"), Ptr{Cint}, ())
       arr = retRndArr()
       unsafe_load(arr, 1)
r[0] = 1960730611
r[1] = 681308252
r[2] = 883636336
r[3] = 1796652726
r[4] = 1091657955
r[5] = 1256249065
r[6] = 2083403509
r[7] = 463289330
r[8] = 1841375418
r[9] = 1100901313
1960730611

```

The function unsafe\_load( **array** , **i** ) returns a single value in **array** at index **i**. Of course I could now declare an array in Julia and assign values. However, how do I interpret data that starts at memory address _arr_ as an Array{Cint, 1} (or Vector{Cint} for that matter) with n values?

**Edit:** **unsafe\_wrap(Vector{Cint}, arr, 10)** achieves that.

Best, Anton

---

<div class="post-metadata">

**Author:** ![GunnarFarneback](https://sea2.discourse-cdn.com/julialang/user_avatar/discourse.julialang.org/gunnarfarneback/32/1827_2.png) [@GunnarFarneback](https://discourse.julialang.org/u/GunnarFarneback)\
**Post date:** [April 22, 2021, 7:45am UTC](https://discourse.julialang.org/t/loading-arrays-from-c-calls/59781/2 "2021-04-22T07:45:23Z")

</div>

Look into the function `unsafe_wrap`.

---

<div class="post-metadata">

**Author:** ![Anton\_Hinneck](https://sea2.discourse-cdn.com/julialang/user_avatar/discourse.julialang.org/anton_hinneck/32/22716_2.png) [@Anton\_Hinneck](https://discourse.julialang.org/u/Anton_Hinneck)\
**Post date:** [April 22, 2021, 7:55am UTC](https://discourse.julialang.org/t/loading-arrays-from-c-calls/59781/3 "2021-04-22T07:55:20Z")

</div>

Thanks, works.

---

<div class="post-metadata">

**Author:** ![foobar\_lv2](https://avatars.discourse-cdn.com/v4/letter/f/ee59a6/32.png) [@foobar\_lv2](https://discourse.julialang.org/u/foobar_lv2)\
**Post date:** [April 22, 2021, 12:07pm UTC](https://discourse.julialang.org/t/loading-arrays-from-c-calls/59781/4 "2021-04-22T12:07:49Z")

</div>

Consider `int* r = malloc(sizeof(int) * 10);` and subsequent `unsafe_wrap(Array, p::Ptr{Cint}, 10; own = true)`.

---

<div class="post-metadata">

**Author:** ![Anton\_Hinneck](https://sea2.discourse-cdn.com/julialang/user_avatar/discourse.julialang.org/anton_hinneck/32/22716_2.png) [@Anton\_Hinneck](https://discourse.julialang.org/u/Anton_Hinneck)\
**Post date:** [April 23, 2021, 8:41am UTC](https://discourse.julialang.org/t/loading-arrays-from-c-calls/59781/5 "2021-04-23T08:41:21Z")

</div>

I tracked down the problem that inspired this post initially. I changed the sample code in my library to:

```julia
#include <stdio.h>
#include <stdlib.h>
#include <time.h>

/* function to generate and return random numbers */
int getRandom( int *r ) {

   int i;

   /* set the seed */
   srand( (unsigned)time( NULL ) );
  
   for ( i = 0; i < 10; ++i) {
      r[i] = rand();
      printf( "r[%d] = %d\n", i, r[i]);
   }

   return 0;
}

// int main(){
// int r[10];
// getRandom(r);
// printf("First array value: %d \n",r[0]);
// printf("Last array value: %d \n",r[9]);
// return 0;
// }

```

Now calling the following in Julia results in a segfault:

```julia
result = Ptr{Cint}()
ccall(("getRandom", "/home/anton_hinneck/projects/ccall_test/retArray.so"), Ptr{Cint}, (Ptr{Cint},), result)
unsafe_wrap(Vector{Cint}, pointer_from_objref(result), 10)

```

What can I do to fix that? It can always be assumed that I know length and datatype of the array.

---

<div class="post-metadata">

**Author:** ![Anton\_Hinneck](https://sea2.discourse-cdn.com/julialang/user_avatar/discourse.julialang.org/anton_hinneck/32/22716_2.png) [@Anton\_Hinneck](https://discourse.julialang.org/u/Anton_Hinneck)\
**Post date:** [April 23, 2021, 8:49am UTC](https://discourse.julialang.org/t/loading-arrays-from-c-calls/59781/6 "2021-04-23T08:49:44Z")

</div>

Thanks a lot. Yes, there is something about memory allocation that is either bugged or I didn’t wrap my head around properly.

---

<div class="post-metadata">

**Author:** ![simeonschaub](https://sea2.discourse-cdn.com/julialang/user_avatar/discourse.julialang.org/simeonschaub/32/216566_2.png) [@simeonschaub](https://discourse.julialang.org/u/simeonschaub)\
**Post date:** [April 23, 2021, 8:59am UTC](https://discourse.julialang.org/t/loading-arrays-from-c-calls/59781/7 "2021-04-23T08:59:51Z")

</div>

`Ptr{Cint}()` will not actually allocate an array, it’s just a null pointer. What you probably want to do is create a Julia array and pass a pointer to that array to your c function, making sure that the array isn’t cleaned up by Julia’s GC before the ccall is done. Try:

```julia
result = Array{Cint}(undef, 10)
GC.@preserve result begin
    ccall(("getRandom", "/home/anton_hinneck/projects/ccall_test/retArray.so"), Cint, (Ptr{Cint},), result)
end
result

```

---

<div class="post-metadata">

**Author:** ![GunnarFarneback](https://sea2.discourse-cdn.com/julialang/user_avatar/discourse.julialang.org/gunnarfarneback/32/1827_2.png) [@GunnarFarneback](https://discourse.julialang.org/u/GunnarFarneback)\
**Post date:** [April 23, 2021, 9:11am UTC](https://discourse.julialang.org/t/loading-arrays-from-c-calls/59781/8 "2021-04-23T09:11:48Z")

</div>

That looks unnecessarily defensive. From [Calling C and Fortran Code · The Julia Language](https://docs.julialang.org/en/v1/manual/calling-c-and-fortran-code/#Garbage-Collection-Safety:)

> `ccall` automatically arranges that all of its arguments will be preserved from garbage collection until the call returns.

---

<div class="post-metadata">

**Author:** ![simeonschaub](https://sea2.discourse-cdn.com/julialang/user_avatar/discourse.julialang.org/simeonschaub/32/216566_2.png) [@simeonschaub](https://discourse.julialang.org/u/simeonschaub)\
**Post date:** [April 23, 2021, 9:25am UTC](https://discourse.julialang.org/t/loading-arrays-from-c-calls/59781/9 "2021-04-23T09:25:26Z")

</div>

True, in this case you won’t need `GC.@preserve`, but it’s important to keep in mind for more complicated examples.

---

<div class="post-metadata">

**Author:** ![Anton\_Hinneck](https://sea2.discourse-cdn.com/julialang/user_avatar/discourse.julialang.org/anton_hinneck/32/22716_2.png) [@Anton\_Hinneck](https://discourse.julialang.org/u/Anton_Hinneck)\
**Post date:** [April 23, 2021, 9:26am UTC](https://discourse.julialang.org/t/loading-arrays-from-c-calls/59781/10 "2021-04-23T09:26:31Z")

</div>

Simeon, thanks a lot.

---

<div class="post-metadata">

**Author:** ![foobar\_lv2](https://avatars.discourse-cdn.com/v4/letter/f/ee59a6/32.png) [@foobar\_lv2](https://discourse.julialang.org/u/foobar_lv2)\
**Post date:** [April 23, 2021, 10:30am UTC](https://discourse.julialang.org/t/loading-arrays-from-c-calls/59781/11 "2021-04-23T10:30:41Z")

</div>

The main issue was with your C code: `int r[10];` does not allocate `int[10]` on the heap, it allocates it on the stack. This means that its lifetime ends once the function returns – so returning a ponter to `r` is a sure way to use-after-free. So you need to `malloc` the thing on the heap.

Now since you allocated something on the unmanaged C heap, you better figure out when to `free` it, or be sure that this memory leak is OK for your application. You can do this manually by calling `free` from C, or manually by calling `ccall(:free, ...` from julia.

Alternatively, you can promise the julia runtime that nobody else holds a pointer to the `malloc`ed memory, via `own = true`. Then the managed julia runtime takes possession of the allocation, freeing it when the array gets garbage collected, potentially `realloc`ed when you `push!` into the array, etc.
