2014-02-27 30 views
0

我正在开发一个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:我应该给指针的指针StructA在调用foo2的地址?

__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. 
    ... 
} 

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

+0

为什么你将指针传递给'foo1()'或'foo2()'的指针? – Macattack

+0

@Macattack,因为我需要在'kernel'上反映值的赋值。 – mrei

回答

2

这应该是你需要的。

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]; 
+0

谢谢,我会尽力的。我倾向于过分复杂的东西。指针指针传递的思想来自理查德·里斯在“理解和使用C指针”中的第3章'指针和函数'第61页__Passing和由指针返回___:“当数据是一个指针时需要修改,然后我们将它作为指针传递给指针“。 – mrei

+0

@mrei确切地说,“当数据是需要修改的指针时,我们将它作为指针传递给指针”这与您的情况有所不同。作者想修改指针,而不是它指向的内容,在这种情况下修改指针,你需要发送指针指针。但你不修改指针。想象一个像房子地址这样的指针,在编程方面,地址指向一些内存而不是房子,你可以给这个地址给其他人(通过指针指向函数) – tesseract

+0

@tessaract我在想你到底在写什么,张贴我以前的评论。谢谢! – mrei