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.

  • 写回答

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

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥100 求数学坐标画圆以及直线的算法
  • ¥100 c语言,请帮蒟蒻写一个题的范例作参考
  • ¥15 名为“Product”的列已属于此 DataTable
  • ¥15 安卓adb backup备份应用数据失败
  • ¥15 eclipse运行项目时遇到的问题
  • ¥15 关于#c##的问题:最近需要用CAT工具Trados进行一些开发
  • ¥15 南大pa1 小游戏没有界面,并且报了如下错误,尝试过换显卡驱动,但是好像不行
  • ¥15 自己瞎改改,结果现在又运行不了了
  • ¥15 链式存储应该如何解决
  • ¥15 没有证书,nginx怎么反向代理到只能接受https的公网网站