亚洲在线久爱草,狠狠天天香蕉网,天天搞日日干久草,伊人亚洲日本欧美

為了賬號安全,請及時綁定郵箱和手機立即綁定
已解決430363個問題,去搜搜看,總會有你想問的

如何調用作為參數接收的 C 函數

如何調用作為參數接收的 C 函數

Go
皈依舞 2023-07-17 16:24:53
我想使用 Go 庫,并在 C 中進行一些調整。我制作了 GoAdder Go 函數,它有 3 個參數 int x、y 和函數類型 f。GoAdder 函數將調用 f 參數。加法器package mainimport "fmt"import "C" //export Ftesttype Ftest func(C.int);//export GoAdderfunc GoAdder(x, y int, f Ftest) int {    fmt.Printf("Go says: adding %v and %v\n", x, y)     f(10);     return x + y}func main() {} // Required but ignored我在上面將 go 包構建為名為 libadder.a 的靜態庫,如下所示:go build -buildmode=c-archive -o libadder.a adder.go然后我寫了下面的C++代碼。主程序#include <stdio.h>#include "adder/libadder.h"void a( GoInt a ){  printf("Hello %d", a);}int main() {  printf("C says: about to call Go...\n");  int total = GoAdder(1, 7, &a);  printf("C says: Go calculated our total as %i\n", total);  return 0;}我已經整理了這樣的來源:gcc -pthread -o static_go_lib main.c adder/libadder.a執行上面的代碼時出現錯誤unexpected fault address 0x0fatal error: fault[signal SIGSEGV: segmentation violation code=0x80 addr=0x0 pc=0x563c99b74244]goroutine 17 [running, locked to thread]:...如何在go函數GoAdder中獲取正確的C函數地址a?我引用了https://github.com/draffensperger/go-interlang/tree/master/c_to_go/static_go_lib
查看完整描述

1 回答

?
30秒到達戰場

TA貢獻1828條經驗 獲得超6個贊

C函數只是跳轉指針,而golang的回調是復雜的結構體,并且無法轉換它們。只有一種(安全)方法來調用 C 函數指針:1)在某處聲明:


//go:linkname cgocall runtime.cgocall

//go:nosplit

func cgocall(fn, arg unsafe.Pointer /* may be uintptr */) int32

2)另外,要保證類型安全:


func GoAdder(x, y C.int, f unsafe.Pointer /*  don't sure if this available, mb C.uintptr_t */) C.int

3)C函數應該以指針(指向任何東西)作為參數


void a(GoInt *a)

(我會使用本機類型)


4)


ten := 10

cgocall(f, unsafe.Pointer(&ten))

(如果你想傳遞幾個參數,它應該是結構體)


查看完整回答
反對 回復 2023-07-17
  • 1 回答
  • 0 關注
  • 122 瀏覽
慕課專欄
更多

添加回答

舉報

0/150
提交
取消
微信客服

購課補貼
聯系客服咨詢優惠詳情

幫助反饋 APP下載

慕課網APP
您的移動學習伙伴

公眾號

掃描二維碼
關注慕課網微信公眾號