Created
January 20, 2014 09:50
-
-
Save jouyouyun/8517565 to your computer and use it in GitHub Desktop.
cgo test
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#include "test.h" | |
void SetFunc() | |
{ | |
InternalFunc(); | |
} |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
package main | |
// #include "test.h" | |
import "C" | |
import "fmt" | |
var function func() | |
//export InternalFunc | |
func InternalFunc() { | |
function() | |
} | |
func Register(fnct func()) { | |
function = fnct | |
C.SetFunc() | |
} | |
func test() { | |
fmt.Println("How should I do it") | |
} | |
func main() { | |
Register(test) | |
} |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#ifndef __TEST_H__ | |
#define __TEST_H__ | |
void SetFunc(); | |
extern void InternalFunc(); | |
#endif |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
2 problems.
test.c
missing#include "_cgo_export.h"
我理解
_cgo_export.h
能让 C 代码访问 Go 导出的方法。 并且只能在go代码中不能直接被引入的地方。go build 先把test.go
用cgo编译成_obj
。如果_cgo_export.h
在 test.h 中 (test.go中直接 include的 test.h) 或者直接在 test.go 中, 可是这时候, 这个_cgo_export.h
还没有被cgo生成。所以会编译报错说找不到_cgo_export.h
void InternalFunc();
intest.h
is enoughextern void InternalFunc();
中的extern
完全没有必要。表面但原因是: 这里就是纯粹的cgo 调用C的方法。。。 官方文档没有说要用extern
才能掉到吧。