3

I can pass a C function pointer to a C function, but passing it to a go function gives invalid operation.

I have 100 go functions wrapping C functions and most share the same setup and arguments so I wanted to implement one go function that can take a C function pointer to make this easier to maintain.

package main

/*
#include <stdio.h>
typedef void (*func_t)(int);
void this_works(int a, func_t f){
    f(a);
}
void tst(int a) {
    printf("YAY\n");
}
*/
import "C"

func this_does_not_work( fp C.func_t ) {
    fp(2) // invalid operation: cannot call non-function fp (variable of type _Ctype_func_t)
}

func main() {
    C.this_works(1, C.func_t(C.tst))
    this_does_not_work( C.func_t(C.tst) )
}

1 Answer 1

1

Impossible, but what's wrong with using a helper?

package main

/*
#include <stdio.h>
typedef void (*func_t)(int);
void this_works(int a, func_t f){
    f(a);
}
void tst(int a) {
    printf("YAY\n");
}

void call_my_c_func(func_t f, int a)
{
    f(a);
}
*/
import "C"

func this_does_not_work(fp C.func_t) {
    C.call_my_c_func(fp, 2)
}

func main() {
    C.this_works(1, C.func_t(C.tst))
    this_does_not_work(C.func_t(C.tst))
}

Basically, you will use C.call_my_c_func(fp, a) instead of fp(a) where applicable—not very beautiful but works.

Sign up to request clarification or add additional context in comments.

2 Comments

Ah of course thanks! I'm concerned with performance, but this doesn't materially affect it.
@Craftables, even if Go would allows such "direct" ("transparent"?) calls to C you were thinking of, the mechanism it would have to exploit to do them would necessarily have the same performance you will have in the case with the helper; if you're interested, there I've explained to someone the basics of how Go calls to C. If you meant that the extra C call in this chanin affects performance, then yes, it does, but I'm sure in such simplistic case (two machine-word-sized arguments and no return value) the overhead will indeed be negligible.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.