title: Using host class member pointing to device memory in device code
body: <p>I want to have an instance of a Container class allocating some device and host memory on initialization. I want to use the allocated memory in device code, without passing the actual pointer (for API reasons).</p>
  
  <p>How do I create a global <code>__device__</code> pointer to the member pointing to the device memory? I am happy to use thrust if that helps.</p>
  
  <p>Here is a small example:</p>
  
  <pre><code>#include &lt;iostream&gt;
  
  
  struct Container {
      int *h_int = (int*)malloc(4*sizeof(int));
      int *d_int;
      Container() {
          h_int[0] = 6; h_int[1] = 6; h_int[2] = 6; h_int[3] = 6;
          cudaMalloc(&amp;d_int, 4*sizeof(int));
          memcpyHostToDevice();
      }
      void memcpyHostToDevice() {
          cudaMemcpy(d_int, h_int, 4*sizeof(int), cudaMemcpyHostToDevice);
      }
      void memcpyDeviceToHost() {
          cudaMemcpy(h_int, d_int, 4*sizeof(int), cudaMemcpyDeviceToHost);
      }
  };
  
  Container stuff;
  
  
  __device__ auto d_int = &amp;stuff.d_int;  // How do I get that right?
  
  
  __global__ void edit() {  // To keep the API simple I do not want to pass the pointer
      auto i = blockIdx.x*blockDim.x + threadIdx.x;
      d_int[i] = 1 + 2*(i &gt; 0) + 4*(i &gt; 2);
  }
  
  
  int main(int argc, char const *argv[]) {
      edit&lt;&lt;&lt;4, 1&gt;&gt;&gt;();
      stuff.memcpyDeviceToHost();
      std::cout &lt;&lt; stuff.h_int[0] &lt;&lt; stuff.h_int[1] &lt;&lt; stuff.h_int[2] &lt;&lt; stuff.h_int[3] &lt;&lt; "\n";
      return 0;
  }
  </code></pre>