0
我試圖調用C函數與他們採取2個int參數相同的簽名。編譯期間出現此錯誤cannot call non-function f (type unsafe.Pointer)
。無法調用unsafe.Pointer(指向C函數)作爲函數
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\n", f(a, b))
}
}
現在,我與包裝C函數的工作與周圍走功能,並添加去功能成片,而不是像這樣
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\n", f(1, 2))
}
}
有沒有辦法從unsafe.Pointer
調用C函數,我使用GO 1.8.1 Linux