如何在 go 中传递 C 函数指针

问题描述 投票:0回答:1

我可以将 C 函数指针传递给 C 函数,但将其传递给 go 函数会产生无效操作。

我有 100 个封装 C 函数的 go 函数,并且大多数共享相同的设置和参数,因此我想实现一个可以采用 C 函数指针的 go 函数,以便更容易维护。

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) )
}
go cgo
1个回答
0
投票

不可能,但是使用助手有什么问题吗?

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))
}

基本上,在适用的情况下,您将使用

C.call_my_c_func(fp, a)
代替
fp(a)
— 不是很漂亮,但有效。

© www.soinside.com 2019 - 2024. All rights reserved.