doupinyan0186
2019-07-12 08:14
浏览 143
已采纳

在C程序中使用golang函数

I have created a golang program to pass some values to c program. I used this example to do so

My simple golang code :

package main

import "C"

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

Then I compiled this using go build -o test.so -buildmode=c-shared test.go

My C code :

#include "test.h"

int *http_200 = Add(); 

When I try to compile it using gcc -o test test.c ./test.so

I get

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

Why I am getting this error? How to initialize that variable properly in my C code.

PS : edited after first comment.

图片转代码服务由CSDN问答提供 功能建议

我创建了一个 golang 程序,将某些值传递给 c 程序。 我用这个例子来做

我简单的golang代码:

  package main 
 
import“ C”  
 
func Add()int {
 var a = 23 
返回
} 
func main(){} 
   
 
 

然后我编译了此文件 使用 进行构建-o test.so -buildmode = c-shared test.go

我的C代码: < pre> #include“ test.h” int * http_200 = Add();

当我尝试使用 gcc -o test test.c ./test.so \进行编译时 n

我得到

int * http_200 = Add(); ^ http_server.c:75:17:错误:初始化器元素不是常量

为什么会出现此错误? 如何在我的C代码中正确初始化该变量。

PS:在第一次注释后进行编辑。

  • 写回答
  • 好问题 提建议
  • 关注问题
  • 收藏
  • 邀请回答

1条回答 默认 最新

  • dpl57372 2019-07-12 09:24
    已采纳

    There are a couple of issues here. First is the incompatibility of the types. Go will return a GoInt. Second issues is that the Add() function has to be exported to get the desired header file. If you don't want to change your Go code, then in C you have to use the GoInt which is a long long.

    A complete example is:

    test.go

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

    test.c

    #include "test.h"
    #include <stdio.h>
    
    int main() {
        int number = Add();
        printf("%d
    ", number);
    }
    

    Then compile and run:

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

    23


    A second example using the 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() {}
    

    test.c

    #include "test.h"
    #include <stdio.h>
    
    int main() {
        long long number = Add();
        printf("%lld
    ", number);
    }
    

    Then compile and run:

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

    23

    已采纳该答案
    评论
    解决 无用
    打赏 举报

相关推荐 更多相似问题