Ask Your Question
4

How can a function pointer be transferred between different files in CUDA?

asked 2021-11-04 11:00:00 +0000

qstack gravatar image

edit retag flag offensive close merge delete

1 Answer

Sort by ยป oldest newest most voted
3

answered 2022-01-30 21:00:00 +0000

david gravatar image

In CUDA, function pointers are not supported across different compilation units. Therefore, function pointers cannot be transferred between different files in CUDA.

One possible solution is to use a callback mechanism. The idea is to pass a function pointer from one source file to another source file as a parameter of a function call. The receiver file can store this function pointer and use it later as a callback function.

For example, suppose we have two source files, "main.cu" and "helper.cu". We want to pass a function pointer "foo" defined in "main.cu" to "helper.cu" and use it as a callback function.

In main.cu:

#include <stdio.h>
#include "helper.cuh"

void foo(int val) {
    printf("In foo, val = %d\n", val);
}

int main() {
    // Pass the function pointer "foo" as a parameter of the function call
    helper(foo);
    return 0;
}

In helper.cu:

#include <stdio.h>

// Define the function pointer type
typedef void (*FP)(int);

// Declare the helper function that takes a function pointer as a parameter
void helper(FP func) {
    printf("In helper\n");
    // Call the function pointer as a callback function
    func(42);
}

In helper.cuh:

void  helper(FP func);

Finally, compile and link the two source files together, and run the program:

$ nvcc main.cu helper.cu
$ ./a.out
In helper
In foo, val = 42
edit flag offensive delete link more

Your Answer

Please start posting anonymously - your entry will be published after you log in or create a new account. This space is reserved only for answers. If you would like to engage in a discussion, please instead post a comment under the question or an answer that you would like to discuss

Add Answer


Question Tools

Stats

Asked: 2021-11-04 11:00:00 +0000

Seen: 20 times

Last updated: Jan 30 '22