2014-02-27 29 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