drv13270 2015-04-13 13:15
浏览 95
已采纳

从c调用go函数时出错

New to go here. Tried to call go function from C but suffered some compiling issues

Here is the go script

package main
// #cgo CFLAGS: -Wno-error=implicit-function-declaration
// #include <stdlib.h> 
// #include "wrapper.c"
import "C"
//import "unsafe"
import "fmt"
//import "time"

//export dummy
func dummy() int {
    fmt.Println("hi you");
    return 0
}

func main() {
    C.testc()
}

Here is the wrapper

#include <sys/types.h>
#include <stdio.h>
#include <errno.h>
#include <string.h>

extern int dummy();

void testc(){
    dummy();
}

When running it, got error

xyz@xyz-HP:~/learn/go$ go run reader.go 
# command-line-arguments
In file included from $WORK/command-line-arguments/_obj/_cgo_export.c:2:0:
reader.go:30:14: error: conflicting types for ‘dummy’
In file included from reader.go:3:0,
                 from $WORK/command-line-arguments/_obj/_cgo_export.c:2:
./wrapper.c:6:12: note: previous declaration of ‘dummy’ was here
/tmp/go-build528677551/command-line-arguments/_obj/_cgo_export.c:8:7: error: conflicting types for ‘dummy’
In file included from reader.go:3:0,
                 from $WORK/command-line-arguments/_obj/_cgo_export.c:2:
./wrapper.c:6:12: note: previous declaration of ‘dummy’ was here
  • 写回答

1条回答 默认 最新

  • dongmi5015 2015-04-13 13:25
    关注

    You don't need to declare dummy in your C file. Here's how I split your code to make it work. I put the C function exporting in an .h file, and the body itself in a .c file, and included only the h file in the go code.

    dummy.h:

    void testc();
    

    dummy.c:

    #include <sys/types.h>
    #include <stdio.h>
    #include <errno.h>
    #include <string.h>
    
    
    void testc(){
        dummy();
    }
    

    main.go:

    package main
    
    // #cgo CFLAGS: -Wno-error=implicit-function-declaration
    // #include <stdlib.h>
    // #include "dummy.h"
    import "C"
    
    import "fmt"
    
    //export dummy
    func dummy() int {
        fmt.Println("hi you")
        return 0
    }
    
    func main() {
        C.testc()
    }
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥15 下图接收小电路,谁知道原理
  • ¥15 装 pytorch 的时候出了好多问题,遇到这种情况怎么处理?
  • ¥20 IOS游览器某宝手机网页版自动立即购买JavaScript脚本
  • ¥15 手机接入宽带网线,如何释放宽带全部速度
  • ¥30 关于#r语言#的问题:如何对R语言中mfgarch包中构建的garch-midas模型进行样本内长期波动率预测和样本外长期波动率预测
  • ¥15 ETLCloud 处理json多层级问题
  • ¥15 matlab中使用gurobi时报错
  • ¥15 这个主板怎么能扩出一两个sata口
  • ¥15 不是,这到底错哪儿了😭
  • ¥15 2020长安杯与连接网探