array of Structures in ArrayFire

[Old posts from the commercial version of ArrayFire] Discussion of ArrayFire using CUDA or OpenCL.

Moderator: pavanky

array of Structures in ArrayFire

Postby anishk25 » Sat Dec 21, 2013 4:30 pm

Hi,

I am trying to make an array of structures in C++ using array fire but I get a compilation error. Here is my Code

Code: Select all
#include <arrayfire.h>
#include <af/utils.h>
struct car{
   unsigned int num_wheels;
};

using namespace af;

int main(){

    struct car h_cars[3];
    h_cars[0].num_wheels = 4;
    h_cars[1].num_wheels = 8;
    h_cars[2].num_wheels = 16;

    array d_cars(3,h_cars);

    return 0;
}


Here is the compile error I am getting

/tmp/ccsFX5VI.o: In function `main':
hello_world.cpp:(.text.startup+0x32): undefined reference to `af::array::array<car>(unsigned int, car const*, af::af_source_t, unsigned int)'
collect2: ld returned 1 exit status
make: *** [hello_world_cuda] Error 1


Does Array Fire not allow for an array of structures?
anishk25
 
Posts: 4
Joined: Wed Dec 18, 2013 9:00 pm

Re: array of Structures in ArrayFire

Postby pavanky » Sat Dec 21, 2013 4:45 pm

Hi Anishk,

The only supported types are float, double, int, unsigned int, bool and complex (single and double precision).

Also on the GPU array of structs is less efficient than struct of arrays.

For example

Code: Select all
typedef struct
{
 float *val;
 int len;
 // Other things in the struct
} mytype;
int main()
{
  mytype var;
  var.val = new float[100];
  var.len = 100;
}


would be better than the following

Code: Select all
typedef struct {
 float val;
 // Other things in struct.
} mytype;

int main()
{
  mytype var[100];
}


This ensures proper data alignment when reading from memory. This is one of the reasons we stick with the basic types in arrayfire.

However this does not mean you can not use custom types with arrayfire. For example, you can change struct of arrays (as mentioned in code sample 1) to something like the following.

Code: Select all
typedef struct
{
  array arr;
 // Other things in struct.
} myarraytype;

int main()
{
 mytype A = mytype_alloc(100);
 myarraytype B;
 B.arr = array(A.len, A.val);
}


This would be much easier if you were using c++ vectors and constructors too, like this.

Code: Select all
class mytype
{
 public:
  std::vector<float> val;
 mytype(int len) { val = std::vector<float>(len) }
};

class myarraytype
{
 public:
 af::array arr;
 myarraytype(mytype A) { arr = af::array(A.size(), &A[0]); }
};

int main()
{
 mytype A(100);
 // Populate A
...
...
// Convert to Array
 myarraytype Arr(A);
}

Pavan Yalamanchili,
ArrayFire
--
~ If it is not broken, you have not tried hard enough ~
User avatar
pavanky
Site Admin
 
Posts: 1123
Joined: Mon Mar 15, 2010 7:39 pm
Location: Atlanta, GA


Return to [archive-commercial] Programming & Development with ArrayFire

cron