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 js调用html页面需要隐藏某个按钮
  • ¥15 ads仿真结果在圆图上是怎么读数的
  • ¥20 Cotex M3的调试和程序执行方式是什么样的?
  • ¥20 java项目连接sqlserver时报ssl相关错误
  • ¥15 一道python难题3
  • ¥15 牛顿斯科特系数表表示
  • ¥15 arduino 步进电机
  • ¥20 程序进入HardFault_Handler
  • ¥15 oracle集群安装出bug
  • ¥15 关于#python#的问题:自动化测试