douyingbei1458 2017-05-17 09:00
浏览 225
已采纳

无法调用unsafe.Pointer(指向C函数)作为函数

I'm trying to call C function with same signature they take 2 int arguments. and this error cannot call non-function f (type unsafe.Pointer) appear during compile.

package main

/*
int add(int a, int b) {
  return a+b;
}
int sub(int a, int b) {
  return a-b;
}
*/
import "C"
import (
    "fmt"
    "unsafe"
)

func main() {
    a := C.int(1)
    b := C.int(2)
    fx := make([]unsafe.Pointer, 2)
    fx[0] = C.add
    fx[1] = C.sub
    for _, f := range fx {
        fmt.Printf("Result: %d
", f(a, b))
    }
}

Now I'm working around with wrap C function with go function and add go function into slice instead like this

package main

/*
int add(int a, int b) {
  return a+b;
}
int sub(int a, int b) {
  return a-b;
}
*/
import "C"
import (
    "fmt"
)

func add(a, b int) int {
    return (int)(C.add(C.int(a), C.int(b)))
}

func sub(a, b int) int {
    return (int)(C.sub(C.int(a), C.int(b)))
}

func main() {
    fx := [](func(int, int) int){
        add, sub,
    }
    for _, f := range fx {
        fmt.Printf("Result: %d
", f(1, 2))
    }
}

Is there any way to call C function from unsafe.Pointer, I'm using GO 1.8.1 Linux

  • 写回答

1条回答 默认 最新

  • dsg41888 2017-05-18 08:31
    关注

    I can solve my problem, according to Go references to C.

    Calling C function pointers is currently not supported, however you can declare Go variables which hold C function pointers and pass them back and forth between Go and C. C code may call function pointers received from Go.

    It's looks like I have to create a bridge function for call C function pointer

    package main
    
    /*
    int add(int a, int b) {
      return a+b;
    }
    int sub(int a, int b) {
      return a-b;
    }
    
    typedef int(*math_fp)(int, int);
    
    const int len_operator = 2;
    
    math_fp math_operators[2] = {
        add, sub
    };
    
    int do_math(math_fp op, int a, int b) {
        return op(a, b);
    }
    */
    import "C"
    import (
        "fmt"
    )
    
    func main() {
        var fnCnt C.int = 2
        var i C.int
        for i = 0; i < fnCnt; i++ {
            op := C.math_fp(C.math_operators[i])
            fmt.Printf("Result: %d
    ", C.do_math(op, 1, 2))
        }
    }
    

    Return expected result

    $ go run src/test.go 
    Result: 3  
    Result: -1
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥15 Mac系统vs code使用phpstudy如何配置debug来调试php
  • ¥15 目前主流的音乐软件,像网易云音乐,QQ音乐他们的前端和后台部分是用的什么技术实现的?求解!
  • ¥60 pb数据库修改与连接
  • ¥15 spss统计中二分类变量和有序变量的相关性分析可以用kendall相关分析吗?
  • ¥15 拟通过pc下指令到安卓系统,如果追求响应速度,尽可能无延迟,是不是用安卓模拟器会优于实体的安卓手机?如果是,可以快多少毫秒?
  • ¥20 神经网络Sequential name=sequential, built=False
  • ¥16 Qphython 用xlrd读取excel报错
  • ¥15 单片机学习顺序问题!!
  • ¥15 ikuai客户端多拨vpn,重启总是有个别重拨不上
  • ¥20 关于#anlogic#sdram#的问题,如何解决?(关键词-performance)