Calling C from Julia (ii) : 2D arrays

Passing 2D arrays from Julia to C is not trivial, nor is is super hard. It just requires a little finessing of the 2D arrays to allow for good migration.

Let us first consider the C function meanFilter().

double meanFilter(int **arr, int row, int col)
    int i, j, sum=0;
    for (i=0; i<row; i=i+1)
        for (j=0; j<col; j=j+1)
             sum = sum + arr[i][j];
    return (double)sum / (row * col);

The code appears as it would in a normal C program, with the function taking three parameters: the array and values that represent the number of rows and columns, and return one value – the mean of the values in the array.

x = zeros(Cint,5,5)
for i=1:5, j=1:5
    x[i,j] = i * j

# Create an array of pointers for every column 
# in the 2D array x

refAr = [pointer(x,i) for i=1:size(x,1):length(x)]

aMean = ccall((:meanFilter, ""),
               Float64, (Ptr{Ptr{Cint}}, Cint, Cint),
               refAr, 5, 5)


The Julia code starts by creating a 5×5 array, x, containing a series of values, of type Cint to align with the type of arr in the C function. Then because arr is a pointer to a pointer to an int, the Julia 2D array x must be converted to an array of pointers. This is done using the Julia function pointer(), with the resulting pointer array stored in refAr.

Now this value can be passed to ccall(), with the same block of four parameters:

(:meanFilter, “”) the name of the C function, and its library file
Float64 the type of the return value from meanFilter()
(Ptr{Ptr{Cint}}, Cint, Cint) the types of the parameters of meanFilter()
refAr, 5, 5 the actual variables to be passed to meanFilter()



One thought on “Calling C from Julia (ii) : 2D arrays

  1. Fuji San says:

    I’m trying to do the same but with a fortran function. But it doesn’t work.
    Any idea how i can do that?

    real(kind=8) function meanFilter(arr, row, col)
    integer, intent(in) :: row, col
    integer, dimension(row,col), intent(in) :: arr
    integer :: i, j, sum

    sum = 0

    do j=1, col
    do i = 1, row
    sum = sum + arr(i,j)
    write(*,*) i, j, arr(i,j), sum
    meanFilter = real(sum,8)/(row*col)
    write(*,*) “mean=”, meanFilter
    end function meanFilter

Leave a Reply

Fill in your details below or click an icon to log in: Logo

You are commenting using your account. Log Out /  Change )

Google+ photo

You are commenting using your Google+ account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )


Connecting to %s

This site uses Akismet to reduce spam. Learn how your comment data is processed.