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

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

導入 cython 生成的 c 共享庫以與 cgo 一起使用

導入 cython 生成的 c 共享庫以與 cgo 一起使用

Go
慕桂英546537 2023-07-10 14:28:21
我想導入一個由 Cython 在 python 3.7 中生成的 c-shared-library,嘗試通過 cgo 來完成。在這種情況下:go版本go1.12.7 linux/amd64Python 3.7.3Cython 版本 0.29.12操作系統:Manjaro 18.0.4內核:x86_64 Linux 5.1.19-1我將繼續:制作一個 python 文件vim pylib.pyx:#!pythoncdef public void hello():     print("hello world!")并運行python -m cython pylib.pyx生成 c-shared-library,我有兩個文件,pylib.c以及pylib.h. 現在,嘗試將它們導入到 golang,因此創建一個 go 文件vim test.go:package main/*#include </usr/include/python3.7m/Python.h>#include "pylib.h"*/import "C"import "fmt"func main() {   C.hello()   fmt.Println("done")}最后,我運行go run test.go:我有以下輸出:# command-line-arguments/usr/bin/ld: $WORK/b001/_x002.o: in function `_cgo_51159acd5c8e_Cfunc_hello':/tmp/go-build/cgo-gcc-prolog:48: undefined reference to `hello'collect2: error: ld returned 1 exit status我也嘗試將其導入到 c 中,但遇到了類似的輸出,如下所示:undefined reference to `hello'ld returned 1 exit status我不知道該怎么辦,請幫助我。:(
查看完整描述

1 回答

?
月關寶盒

TA貢獻1772條經驗 獲得超5個贊

我運行 go run test.go:我有以下輸出:


# command-line-arguments

/usr/bin/ld: $WORK/b001/_x002.o: in function `_cgo_51159acd5c8e_Cfunc_hello':

/tmp/go-build/cgo-gcc-prolog:48: undefined reference to `hello'

collect2: error: ld returned 1 exit status

我們可以使用以下代碼生成等效的錯誤消息。


package main


/*

#include <math.h>

*/

import "C"

import "fmt"


func main() {

    cube2 := C.pow(2.0, 3.0)

    fmt.Println(cube2)

}

輸出:


$ go run cube2.go

# command-line-arguments

/usr/bin/ld: $WORK/b001/_x002.o: in function `_cgo_f6c6fa139eda_Cfunc_pow':

/tmp/go-build/cgo-gcc-prolog:53: undefined reference to `pow'

collect2: error: ld returned 1 exit status

在這兩種情況下,ld(鏈接器)在查看通常的位置后都找不到 C 函數:undefined reference to 'pow'或undefined reference to 'hello'。


讓我們告訴您在 C庫中cgo哪里可以找到 C函數:。powmathm


對于cgo,使用ld標志,


#cgo LDFLAGS: -lm

GCC:3.14 鏈接選項


-llibrary

    Search the library named library when linking.

更新之前的代碼,


package main


/*

#cgo LDFLAGS: -lm

#include <math.h>

*/

import "C"

import "fmt"


func main() {

    cube2 := C.pow(2.0, 3.0)

    fmt.Println(cube2)

}

輸出:


$ go run cube2.go

8

$

這說明了一個基本cgo原則:包含 C 庫的 C 頭文件并指向 C 庫的位置。


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

添加回答

舉報

0/150
提交
取消
微信客服

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

幫助反饋 APP下載

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

公眾號

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