首页
学习
活动
专区
工具
TVP
发布
社区首页 >问答首页 >从C++调用Go函数

从C++调用Go函数
EN

Stack Overflow用户
提问于 2011-05-25 22:02:13
回答 3查看 46.3K关注 0票数 157

我正在尝试创建一个用Go编写的静态对象,以便与C程序(例如,内核模块或其他程序)进行接口。

我找到了关于从Go调用C函数的文档,但我还没有找到太多关于如何从go调用C函数的文档。我发现这是可能的,但很复杂。

这是我发现的:

Blog post about callbacks between C and Go

Cgo documentation

Golang mailing list post

有没有人有这方面的经验?简而言之,我正在尝试创建一个完全用Go编写的PAM模块。

EN

回答 3

Stack Overflow用户

回答已采纳

发布于 2011-05-27 10:02:21

你可以从C调用Go代码,但这是一个令人困惑的命题。

您链接到的博客帖子中概述了该过程。但我可以看出,这并不是很有帮助。下面是一个简短的代码片段,没有任何不必要的部分。这应该会让事情变得更清晰一些。

代码语言:javascript
复制
package foo

// extern int goCallbackHandler(int, int);
//
// static int doAdd(int a, int b) {
//     return goCallbackHandler(a, b);
// }
import "C"

//export goCallbackHandler
func goCallbackHandler(a, b C.int) C.int {
    return a + b
}

// This is the public function, callable from outside this package.
// It forwards the parameters to C.doAdd(), which in turn forwards
// them back to goCallbackHandler(). This one performs the addition
// and yields the result.
func MyAdd(a, b int) int {
   return int( C.doAdd( C.int(a), C.int(b)) )
}

调用所有内容的顺序如下:

代码语言:javascript
复制
foo.MyAdd(a, b) ->
  C.doAdd(a, b) ->
    C.goCallbackHandler(a, b) ->
      foo.goCallbackHandler(a, b)

这里要记住的关键是,回调函数在Go端必须标记为//export注释,在C端必须标记为extern。这意味着你想要使用的任何回调都必须在你的包中定义。

为了允许包的用户提供自定义回调函数,我们使用与上面完全相同的方法,但我们提供了用户的自定义处理程序(这只是一个常规的Go函数)作为参数,该参数作为void*传递到C端。然后由我们包中的回调处理程序接收并调用。

让我们使用一个我目前正在使用的更高级的示例。在本例中,我们有一个C函数,它执行一项相当繁重的任务:它从USB设备读取文件列表。这可能需要一段时间,所以我们希望通知我们的应用程序它的进度。我们可以通过传入我们在程序中定义的函数指针来做到这一点。每当它被调用时,它只是向用户显示一些进度信息。由于它有一个众所周知的签名,我们可以为它分配自己的类型:

代码语言:javascript
复制
type ProgressHandler func(current, total uint64, userdata interface{}) int

这个处理程序接受一些进度信息(当前接收的文件数和文件总数)以及一个interface{}值,该值可以保存用户需要它保存的任何内容。

现在,我们需要编写C并执行管道操作,以允许我们使用此处理程序。幸运的是,我希望从库中调用的C函数允许我们传入void*类型的用户数据结构。这意味着它可以容纳我们想让它容纳的任何东西,没有任何问题,我们将把它带回Go世界。为了完成所有这些工作,我们没有直接从Go调用库函数,但是我们为它创建了一个C包装器,我们将其命名为goGetFiles()。实际上,这个包装器提供了对C库的Go回调,以及一个userdata对象。

代码语言:javascript
复制
package foo

// #include <somelib.h>
// extern int goProgressCB(uint64_t current, uint64_t total, void* userdata);
// 
// static int goGetFiles(some_t* handle, void* userdata) {
//    return somelib_get_files(handle, goProgressCB, userdata);
// }
import "C"
import "unsafe"

请注意,goGetFiles()函数没有将任何用于回调的函数指针作为参数。相反,我们的用户提供的回调被打包在一个自定义结构中,该结构同时包含该处理程序和用户自己的userdata值。我们将其作为userdata参数传递给goGetFiles()

代码语言:javascript
复制
// This defines the signature of our user's progress handler,
type ProgressHandler func(current, total uint64, userdata interface{}) int 

// This is an internal type which will pack the users callback function and userdata.
// It is an instance of this type that we will actually be sending to the C code.
type progressRequest struct {
   f ProgressHandler  // The user's function pointer
   d interface{}      // The user's userdata.
}

//export goProgressCB
func goProgressCB(current, total C.uint64_t, userdata unsafe.Pointer) C.int {
    // This is the function called from the C world by our expensive 
    // C.somelib_get_files() function. The userdata value contains an instance
    // of *progressRequest, We unpack it and use it's values to call the
    // actual function that our user supplied.
    req := (*progressRequest)(userdata)

    // Call req.f with our parameters and the user's own userdata value.
    return C.int( req.f( uint64(current), uint64(total), req.d ) )
}

// This is our public function, which is called by the user and
// takes a handle to something our C lib needs, a function pointer
// and optionally some user defined data structure. Whatever it may be.
func GetFiles(h *Handle, pf ProgressFunc, userdata interface{}) int {
   // Instead of calling the external C library directly, we call our C wrapper.
   // We pass it the handle and an instance of progressRequest.

   req := unsafe.Pointer(&progressequest{ pf, userdata })
   return int(C.goGetFiles( (*C.some_t)(h), req ))
}

这就是我们的C绑定。用户的代码现在非常简单:

代码语言:javascript
复制
package main

import (
    "foo"
    "fmt"
)

func main() {
    handle := SomeInitStuff()

    // We call GetFiles. Pass it our progress handler and some
    // arbitrary userdata (could just as well be nil).
    ret := foo.GetFiles( handle, myProgress, "Callbacks rock!" )

    ....
}

// This is our progress handler. Do something useful like display.
// progress percentage.
func myProgress(current, total uint64, userdata interface{}) int {
    fc := float64(current)
    ft := float64(total) * 0.01

    // print how far along we are.
    // eg: 500 / 1000 (50.00%)
    // For good measure, prefix it with our userdata value, which
    // we supplied as "Callbacks rock!".
    fmt.Printf("%s: %d / %d (%3.2f%%)\n", userdata.(string), current, total, fc / ft)
    return 0
}

这一切看起来都比实际情况复杂得多。与我们前面的示例相反,调用顺序没有改变,但我们在链的末尾获得了两个额外的调用:

顺序如下:

代码语言:javascript
复制
foo.GetFiles(....) ->
  C.goGetFiles(...) ->
    C.somelib_get_files(..) ->
      C.goProgressCB(...) ->
        foo.goProgressCB(...) ->
           main.myProgress(...)
票数 132
EN

Stack Overflow用户

发布于 2013-04-02 17:47:02

如果您使用gccgo,这不是一个令人困惑的命题。它在这里起作用:

foo.go

代码语言:javascript
复制
package main

func Add(a, b int) int {
    return a + b
}

bar.c

代码语言:javascript
复制
#include <stdio.h>

extern int go_add(int, int) __asm__ ("example.main.Add");

int main() {
  int x = go_add(2, 3);
  printf("Result: %d\n", x);
}

Makefile

代码语言:javascript
复制
all: main

main: foo.o bar.c
    gcc foo.o bar.c -o main

foo.o: foo.go
    gccgo -c foo.go -o foo.o -fgo-prefix=example

clean:
    rm -f main *.o
票数 58
EN

Stack Overflow用户

发布于 2016-05-12 04:50:21

随着Go 1.5的发布,答案发生了变化

我前段时间问的这个问题,根据1.5增加的功能再次解决了这个问题

Using Go code in an existing C project

票数 16
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/6125683

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档