class or struct

Hi Forum

Can somebody tell me what is the best option to work with “objects” in cuda?, i.e, a class or a struct?

thanks

Uh… A class is a struct… I think you can even rename every class to struct anyway and it’ll still be recognized by the compiler, assuming C++ syntax.

I don’t know about copying between the device and the host though as address stuff gets easily overwritten in CUDA so structs might actually just be a better option. I’ve never really played with objects in CUDA which I will go do now…

Edit: Okay, I wrote a simple class code in CUDA. I don’t know if you were looking for a good example or not, but I can tell you that this one works. And I think it doesn’t leak any memory. Idk, cuda-memcheck can’t actually seem to detect leaks which I take it means that my GPU just isn’t supported.

The most important thing to do is, if you’re going to use classes, specify what the inline methods can run on. In my case, I don’t think I can ever use my class function on the host.

#include <cuda.h>
#include <stdio.h>

struct object {

public:

   int a;

   __device__ int add(int a, int b) {

      return a+b;
   }
};

__global__ void fcnCall(struct object *device) {

   device->a = device->add(1, 2);

   return;
}

int main(void) {

   struct object *host = (struct object*) malloc(sizeof(*host));

   struct object *device;

   cudaMalloc(&device, sizeof(*host));

   cudaMemcpy(device, host, sizeof(*host), cudaMemcpyHostToDevice);

   fcnCall<<<1, 1>>>(device);

   cudaMemcpy(host, device, sizeof(*host), cudaMemcpyDeviceToHost);

   printf("host integer value : %d\n", host->a);

   cudaFree(device);
   free(host);

   return 0;
}

Hello John

Thanks for your answer, and for the example that you have created.

I have read some books and documents, and authors always work with structures.

I have a old code which work with classes, but I don’t know if the performance is lower than with structs.

That is the motive of my question.

So, im going to use structs.

Thank you very much.

Actually, would you mind posting that code? I’d very much like to see it.

Hello john

I’m Sorry, but the code is too large to post here.

In CUDA, just like regular C++, a class and a struct are almost identical. The only difference is that a struct has a “public:” visibility qualifier by default, and a class has a “private:” by default.

There is absolutely no memory, speed, or functionality difference between them other than that little default.

In practice, most programmers tend to use the types to show the intent of the data. “Plain Old Data”, a dumb structure which doesn’t have methods, is often defined as a struct to remind you of that, with classes reserved for fancy objects with methods and behaviors. But that split is again mere programmer convenience and convention, not a rule, requirement, or performance difference.