为了账号安全,请及时绑定邮箱和手机立即绑定

导入 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 关注
  • 74 浏览
慕课专栏
更多

添加回答

举报

0/150
提交
取消
意见反馈 帮助中心 APP下载
官方微信