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
end

# 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, "myC2.so"),
               Float64, (Ptr{Ptr{Cint}}, Cint, Cint),
               refAr, 5, 5)

println(aMean)

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, “myC2.so”) 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()

 

Advertisements

Leave a Reply

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

WordPress.com Logo

You are commenting using your WordPress.com 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 )

Google+ photo

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

Connecting to %s