【问题标题】:Passing pointers down to three nested functions将指针向下传递给三个嵌套函数
【发布时间】:2014-03-30 04:15:25
【问题描述】:

我正在从事一个 CUDA 项目。但是,这基本上是一个关于指针的 C 概念,与 CUDA 本身没有太大关系。

我不确定我的引用/解除引用指针是否正确完成以反映我的 kernel 函数上的新值(与 C 函数相同,但在 GPU 上完成)。

我的kernel 得到一个指针作为参数:

__global__ kernel(StructA *a)
{
  StructB b;
  foo1(&a, &b); // passing both addresses to foo1
                // I don't need to modify anything on StructA, might in future
                // But, I will assign values to StructB (in foo1 and foo2)
  ...
  // Work with StructB
  ...
}

foo1 的问题:我是否应该在对foo2 的调用中给出指向指针 StructA 的地址?

__device__ foo1(StructA **a, StructB *b) // pointer-to pointer and pointer
{
  int tid = blockIdx.x * blockDim.x + threadIdx.x;
  if( (*a)->elem1[tid] ) // Access to value in elem1[tid]
    foo2(a, &b, tid);    // Pass structures to foo2
  ...
  b->elem3 = 1;          // Assign value to StructB
  ...
}

foo2 的问题:如果我传递 StructA 地址,我将需要 StructA 的第三级指针。但是,我在那个级别的指针上迷失了。

__device__ foo2(StructA **a, StructB **b, int tid)
{
  // Assign value from elem2 in StructA for the thread to elem2 in StructB
  (*b)->elem2 = (*a)->elem2[tid]; // Assign value to StructB from StructA

  // HELP in previous line, not so sure if referencing the in the Structures
  // are done correctly.
  ...
}

我可以粘贴我的实际代码,但不想让事情复杂化。

【问题讨论】:

  • 你为什么将指针传递给foo1()foo2() 的指针?
  • @Macattack 因为我需要将值的分配反映在 kernel 上。

标签: c pointers cuda


【解决方案1】:

这应该是你需要的。

 foo1(a, &b);

__device__ foo1(StructA *a, StructB *b)

   foo2(a, b, tid); //when we are inside foo1, foo1 has the pointers available 
    //so we just pass it to foo2.

__device__ foo2(StructA *a, StructB *b, int tid)

如果您在 foo1 中执行 foo2(a, &b, tid);,您将传递包含指向该结构的指针的指针变量的地址,但这不是必需的,只要您的函数中有指向该结构的指针即可可以通过简单的说将它传递给其他函数

`function_name(structA *pointer_to_strucutA)

关于作业,你所做的是正确的,但不是必须的

(*b)->elem2 = (*a)->elem2[tid]; //this is correct if you pass a pointer to pointer to struct 

如果你遵循我的代码,你真正需要的是

b->elem2 = a->elem2[tid];

【讨论】:

  • 谢谢,我会试试的。我倾向于把事情复杂化。指针传递的想法取自 Richard Reese 的“理解和使用 C 指针”O'Reilly 2013,在第 3 章“指针和函数”第 61 页 通过指针传递和返回:“当数据是需要修改的指针时,我们将其作为指针传递给“指针”。
  • @mrei 确切地说,“当数据是需要修改的指针时,我们将其作为指向指针的指针传递”这与您的情况不同。作者想要修改指针,而不是它指向的内容,在这种情况下要修改指针,您需要发送指向指针的指针。但你没有修改指针。将指针想象为房屋地址,在编程术语中,该地址将指向某个内存而不是房屋,您可以将此地址提供给其他人(将指针传递给函数)
  • @tessaract 我在发布我之前的评论时正在考虑您所写的内容。谢谢!
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2021-07-17
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多