从c调用go函数时出错

时间:2015-04-13 13:15:18

标签: go cgo

新来到这里。试图从C调用go函数但遭遇了一些编译问题

这是go脚本

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()
}

这是包装器

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

extern int dummy();

void testc(){
    dummy();
}

运行时,出现错误

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 个答案:

答案 0 :(得分:1)

您不需要在C文件中声明dummy。这是我如何拆分代码以使其工作。我将C函数导出到.h文件中,并将正文本身放在.c文件中,并且只包含go代码中的h文件。

<强> 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()
}