小编use*_*312的帖子

从C++通过SWIG调用Go回调函数

我正在尝试调用C++函数:

void TestFunc(void(*f)(void)) { f(); }
Run Code Online (Sandbox Code Playgroud)

来自Go Code.

我真的希望它只是将Go函数传递给该函数.我知道我可以将它包装到一个类中,并使用%feature("director")解决它,但这不是我案例中的最佳解决方案.

从我在本页中看到的,Go中的函数指针应该与C++中的相同,所以我尝试了以下.swig文件:

%{
#include "test.h"
%}

%typemap(gotype) FUNC* "func()"
%typemap(in) FUNC* {
  $1 = (void(*)(void))$input;
}
%apply FUNC* { void(*)(void) };

%include "test.h"
Run Code Online (Sandbox Code Playgroud)

我很安静地感到惊讶,它起初工作,但后来注意到它并不总是有效:(.

例如,在此Go代码中,它按预期工作:

import "fmt"
import "test_wrap"

func main() {
  b := false
  test_wrap.TestFunc(func() { b = true })
  fmt.Println(b)  // This actually DOES print "true"!
}
Run Code Online (Sandbox Code Playgroud)

但在其他情况下,它不起作用.例如,这里:

import "fmt"
import "test_wrap"

func main() {
  test_wrap.TestFunc(func() { fmt.Println("SUCCESS") })
  fmt.Println("Done")
}
Run Code Online (Sandbox Code Playgroud)

我真的得到:

SUCCESS
SIGILL: illegal instruction
PC=0x4c20005d000


goroutine …
Run Code Online (Sandbox Code Playgroud)

c++ swig interop language-interoperability go

4
推荐指数
1
解决办法
1396
查看次数

标签 统计

c++ ×1

go ×1

interop ×1

language-interoperability ×1

swig ×1