Hi, I’m trying to copy a struct that looks something like this:
struct.cuh
struct MyStruct{
float value;
};
into a GPU variable:
variable.cuh
#include "struct.cuh"
__constant__ MyStruct myStruct;
So far I’ve tried this:
setter.cu
#include "struct.cuh"
#include "variable.cuh"
void SetStruct(MyStruct* data){
printf("value [CPU] %d\n", data->value);
CUDA_SAFE_CALL(cudaMemcpyToSymbol(myStruct, data, sizeof(MyStruct)));
printf("value [GPU] %d\n", myStruct.value);
}
but this prints the following:
value [CPU]: 100
value [GPU]: 0
the expected result is this:
value [CPU]: 100
value [GPU]: 100
I seriously do not know what is going wrong. Any help would be greatly appreciated.
[code written in browser]
You can’t print device memory from host code.
If you want to print it out, you could launch a kernel and printf from there.
Yes I’ve tried doing that, but the result is the same - “value [GPU]: 0”
njuffa
June 29, 2022, 8:58am
4
#include <stdio.h>
#include <stdlib.h>
struct MyStruct{
float value;
};
__constant__ MyStruct myStruct;
__global__ void printKernel (void)
{
printf ("GPU: myStruct.value = %15.8e\n", myStruct.value);
}
int main (void)
{
for (float data = 1.0f; data < 5.0f; data += 1.0f) {
printf ("CPU: Setting myStruct.value to %15.8e\n", data);
cudaMemcpyToSymbol(myStruct, &data, sizeof myStruct);
printKernel<<<1,1>>>();
cudaDeviceSynchronize(); // flush device-side print buffer
}
return EXIT_SUCCESS;
}
prints something like
CPU: Setting myStruct.value to 1.00000000e+000
GPU: myStruct.value = 1.00000000e+00
CPU: Setting myStruct.value to 2.00000000e+000
GPU: myStruct.value = 2.00000000e+00
CPU: Setting myStruct.value to 3.00000000e+000
GPU: myStruct.value = 3.00000000e+00
CPU: Setting myStruct.value to 4.00000000e+000
GPU: myStruct.value = 4.00000000e+00
I think I know what the problem was: I was passing a pointer to the SetStruct function. After changing it to pass the struct as a reference I get the expected result.