我在 Go 中有一个函数:
func login(user *C.char) *C.char {
cstr := C.CString("Hello World")
defer C.free(unsafe.Pointer(cstr))
return cstr
}
Run Code Online (Sandbox Code Playgroud)
我的红宝石代码如下
module GoLib
extend FFI::Library
ffi_lib './golib.so'
attach_function :login, [:string], :string
end
GoLib.login("User1") #=> "p\x9A\xA0\xDB\x16V"
Run Code Online (Sandbox Code Playgroud)
它不会作为 ruby 字符串返回。我该如何解决这个问题?
我想在 Golang 中编写控制器逻辑并处理 json 和数据库,同时在 C 中使用我的数学处理模型。在我看来,调用 C 函数的开销必须尽可能低,就像设置寄存器 rcx、rdx、rsi、rdi 一样,做一些fastcall 并获得 rax 价值。但我听说cgo 的开销很大
说它我有常见的 fastcall x64 c 函数int64 f(int64 a,b,c,d){return a+b+c+d}我如何从 go 调用它,以获得 go testing.Bbenchmark 中最高的潜在基准分数?
PS 没有指针传递,没有技巧,只是对如何以最健壮的方式访问 C 接口感兴趣
我的目标是比较我的 golang 应用程序的两个 docker 解决方案:
我的 Dockerfile 非常简单,类似于:
FROM ubuntu:20.04
# FROM golang:alpine for alpine based images
# myApp binary is pre-built before running docker build
COPY bin/myApp app/myApp
COPY myApp-config.json app/myApp-config.json
CMD MYAPP_CONFIG=app/myApp-config.json ./app/myApp
Run Code Online (Sandbox Code Playgroud)
对于基于高山的图像,我在这里遇到了同样的问题,由于生成的图像中缺少 CGO 动态链接,因此 /app/myApp 无法启动。我通过在 go build 期间禁用 CGO 来解决这个问题:
CGO_ENABLED=0
Run Code Online (Sandbox Code Playgroud)
由于我对 docker 很陌生,所以我的问题是:
net/http似乎需要在运行时存在 CGO。谢谢!
我有一个非常简单的设置:一个 .go 文件 ( test.go ) 和一个 .c 文件 ( PMDK.c )。我将 .c 文件包含在 Go 中,如下所示:
测试.go:
package main
/*
#include "PMDK.c"
#cgo pkg-config: libpmem
*/
import "C"
func main() {
C.helloWorld()
}
Run Code Online (Sandbox Code Playgroud)
当我运行go run test.go时,它只构建一次。无论我对PMDK.c进行什么更改,我的程序每次都有完全相同的行为。
我还尝试了go build test.go,这导致了相同的结果。最后,在CGo 不编译同一目录中的 C 文件之后,我只是执行了go build。这不起作用,因为我必须创建一个 .mod 文件(go build test.go)。然后,问题是PMDK.c中的三个函数(helloWorld和其他两个函数)据说被定义了多次。我无法让它构建我的更改。顺便说一句,如果我将源文件复制/移动到另一个目录并在那里构建它们,则更改将适用(仅一次,再次)。
我已经查看了usr/bin/ld:cannot find -l<nameOfTheLibrary>中的答案,但它们都不适用于此上下文。
我刚刚买了一台新笔记本电脑并设置了 Go。一个简单的 hello world 程序可以工作,但是当我尝试一个更复杂的程序时,我得到:
go run .
# runtime/cgo
/usr/bin/ld: cannot find -lavcodec
/usr/bin/ld: cannot find -lavformat
/usr/bin/ld: cannot find -lavutil
/usr/bin/ld: cannot find -lswscale
/usr/bin/ld: cannot find -lswresample
/usr/bin/ld: cannot find -lavdevice
/usr/bin/ld: cannot find -lavfilter
collect2: error: ld returned 1 exit status
Run Code Online (Sandbox Code Playgroud)
我不确定我的程序中哪里发生了错误,因为上面是我得到的唯一输出。
$ gcc --version
gcc (Ubuntu 10.3.0-1ubuntu1) 10.3.0
Run Code Online (Sandbox Code Playgroud)
编辑:这是一个重现错误的小样本:
package main
import "net/http"
func main() {
cli := &http.Client{}
rsp, err := cli.Get("https://google.com")
if err != nil {
panic(err)
}
defer …Run Code Online (Sandbox Code Playgroud) cgo ×5
go ×5
c ×2
ffi ×2
alpine-linux ×1
docker ×1
go-build ×1
linux ×1
performance ×1
ruby ×1