Trouble translating to C API

22 views
Skip to first unread message

Alex Shroyer

unread,
Oct 25, 2021, 10:37:56 AM10/25/21
to ArrayFire Users
Hi, I can build and run a C++ example and get the expected output. However when I try to translate this to use the C API, I get an error.

This C++ code works:
$ cat main.c
#include<arrayfire.h>
int main(void) {
    af::array M1 = af::randu(2,4);
    af::array M2 = af::randu(4,1);
    af::array result = af::matmul(M1, M2);
    af_print(result);
}
$ g++ -std=c++11 main.cpp -I/opt/arrayfire/include -lafcpu -L/opt/arrayfire/lib64
$ ./a.out
result
[2 1 1 1]
    0.9704
    0.3218

I attempted to translate this into a C API version. It compiles, but the print function produces "208" error (AF_ERR_DEVICE). What causes this error and how can I fix it?

Below is the C version, compile command, and output:
$ cat main.c
#include<arrayfire.h>
#include<stdio.h>
int main() {
    af_array M1, M2, result;
    dim_t d1[] = {2, 4};
    dim_t d2[] = {4, 1};
    if (AF_SUCCESS != af_randu(&M1, 2, d1, f64)) return 1;
    if (AF_SUCCESS != af_randu(&M2, 2, d2, f64)) return 1;
    if (AF_SUCCESS != af_matmul(&result, M1, M2, AF_MAT_NONE, AF_MAT_NONE)) return 1;
    printf("before\n");
    printf("%d\n", af_print_array(&result));
    printf("after\n");
    return 0;
}
$ gcc -std=c11 main.c -I/opt/arrayfire/include -lafcpu -L/opt/arrayfire/lib64
$ ./a.out
before
208
after

Thanks in advance!

Alex Shroyer

unread,
Oct 25, 2021, 10:40:23 AM10/25/21
to ArrayFire Users
Silly mistake, I should not have used &result, just result. Works now!

Alex Shroyer

unread,
Oct 25, 2021, 10:50:25 AM10/25/21
to ArrayFire Users
A follow-up question: what is the rationale behind some array parameters being passed by pointer and others being passed by value?

uma...@gmail.com

unread,
Oct 25, 2021, 12:02:11 PM10/25/21
to ArrayFire Users
Typically, the af_array objects that are assigned will be passed as a pointer and the others are passed as value because they are input and will not be changed in the operation. The af_array is just a handle to an internal data structure that represents the af_array object. Its like passing in a void*.

Umar

Alex Shroyer

unread,
Oct 25, 2021, 12:25:34 PM10/25/21
to ArrayFire Users
Thanks Umar, that makes sense.
Reply all
Reply to author
Forward
0 new messages