Ask Your Question

Revision history [back]

click to hide/show revision 1
initial version

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