c - 在 C 程序中使用 golang 函数

标签 c go cgo

我创建了一个 golang 程序来将一些值传递给 c 程序。 I used this example to do so

我的简单 golang 代码:

package main

import "C"

func Add() int {
        var a = 23
        return a 
 }
func main() {}

然后我用 go build -o test.so -buildmode=c-shared test.go

我的 C 代码:

#include "test.h"

int *http_200 = Add(); 

当我尝试使用 gcc -o test test.c ./test.so 编译它时

我明白了

int *http_200 = Add(); ^ http_server.c:75:17: error: initializer element is not constant

为什么我会收到这个错误?如何在我的 C 代码中正确初始化该变量。

PS:第一条评论后编辑。

最佳答案

这里有几个问题。首先是类型的不兼容。 Go 将返回一个 GoInt。第二个问题是必须导出 Add() 函数以获得所需的头文件。如果您不想更改您的 Go 代码,那么在 C 中您必须使用 GoInt,它是一个 long long

一个完整的例子是:

test.go

package main

import "C"

//export Add
func Add() C.int {
    var a = 23
    return C.int(a)
}

func main() {}

测试.c

#include "test.h"
#include <stdio.h>

int main() {
    int number = Add();
    printf("%d\n", number);
}

然后编译运行:

go build -o test.so -buildmode=c-shared test.go
gcc -o test test.c ./test.so &&
./test

23


第二个使用 GoInt 的例子: test.go

package main

import "C"

//export Add
func Add() int { // returns a GoInt (typedef long long GoInt)
    var a = 23
    return a
}

func main() {}

测试.c

#include "test.h"
#include <stdio.h>

int main() {
    long long number = Add();
    printf("%lld\n", number);
}

然后编译运行:

go build -o test.so -buildmode=c-shared test.go
gcc -o test test.c ./test.so &&
./test

23

关于c - 在 C 程序中使用 golang 函数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/57002881/

相关文章:

go - SQLMock 和 Gorm : Mocking Postgres Insert

c - 如何在CGO函数中操作C字符数组?

与 Go 之间的 C 指针转换

go - 导入cgo时无法运行init()函数,且导入 “C”

c - 套接字选择失败且操作正在进行 - 非阻塞模式

C - 解压缩 Gzipped http 响应

go - 使用 GO111MODULE 安装 buffalo 导致 go get : error loading module requirements

go - 使用 Go 驱动程序在 RethinkDB 中按嵌套对象排序

c - 如何读取单个文件中字符串的最后 n 个字符?

c - 如何在不使用字符串库的情况下查找另一个字符数组中是否存在一个字符数组?