embedding ArrayFire arrays in other C++ classes

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

Moderator: pavanky

embedding ArrayFire arrays in other C++ classes

Postby malcolm » Mon Jan 30, 2012 11:55 am

Just received an email from a long-time Jacket developer now working with ArrayFire and thought I'd share it since it comes up now and then:
Hi,
Can you give me a quick summary of C++ support in ArrayFire? In particular, if I create a class with GPU arrays and methods, will that class behave as usual wrt construction, destruction, referencing, etc? Are there any constraints on use of ArrayFire arrays within classes?

Also, do you know if Cuda supports C++ classes?
Thanks


ArrayFire plays nice with regular C++ classes, i.e. it has constructors and destructors that chain naturally when embedded in other objects. Some example code follows. Be sure to copy over the necessary fields in your copy-constructor. Your class deconstructor will automatically propagate to destruct the arrays inside your class.

Code: Select all
#include <stdio.h>
#include <arrayfire.h>
using namespace af;

class Foo {
public:
    array m_field;
    Foo() { m_field = randu(1,2); } // uniform
    ~Foo() { } // m_field is destructed automatically

    // if you have a copy constructor, then copy the field
    Foo(const Foo &x) {
        // ArrayFire just makes a shared reference here not a deep copy (copy-on-write semantics)
        m_field = x.m_field;
    }
};


static void pass_by_ref(Foo &A) {
    print(A.m_field);
}
static void pass_by_val(Foo A) {
    print(A.m_field);
    A.m_field(0) = -1; // modify my copy
    print(A.m_field);
}

int main() {
    Foo A;
    print(A.m_field);
    pass_by_ref(A);
    pass_by_val(A);
    std::cout << "demonstrate original is unchanged:\n";
    print(A.m_field);

    return 0;
}


Code: Select all
 $ make run
g++  -Wall -Werror -I/home/malcolm/arrayfire/include -I/usr/local/cuda/include -O2 -DNDEBUG  -c -o foo.o foo.cpp
cc -lrt -L/home/malcolm/arrayfire/lib -laf  -L/usr/local/cuda/lib -lcuda -lcudart -lpthread -lstdc++ -Wl,-rpath,/home/malcolm/arrayfire/lib,-rpath,/home/malcolm/arrayfire/lib,-rpath,/usr/local/cuda/lib  foo.o   -o foo
for F in foo; do echo $F; ./${F} -; done
foo
A.m_field =
        0.7402     0.9210

A.m_field =
        0.7402     0.9210

A.m_field =
        0.7402     0.9210

A.m_field =
       -1.0000     0.9210

demonstrate original is unchanged:
A.m_field =
        0.7402     0.9210
James Malcolm (malcolm@accelereyes.com)
User avatar
malcolm
 
Posts: 600
Joined: Sat Jun 14, 2008 11:00 pm

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

cron