2

我想用“go build”来构建我的项目。我还没有找到任何文档如何将 swig 与 go build 过程集成。而且也很重要,它应该是一个 C++ 例子 C 很简单。

foo.swig

/* foo.i */
%module foo
%{
#include "foo.h"
%}
%include "foo.h"

foo.h

#pragma once
int foo(int a, int b);
class MyClass {
    int a,b,c;
public:
    MyClass(int a, int b, int c): a(a),b(b),c(c) {}
    int foo() {
        return (a+b)*c;
    }
    int bar() {
        return a*(b+c);
    }
};

foo.cpp

#include "foo.h"
int foo(int a, int b){
    return a*b;
}

main.go

package foo
import "fmt"
func main(args []string) {
    fmt.Println("Hello World!")
    fmt.Println(foo.foo(12, 17))
}

输出

arne@ad-X201t ~/g/s/g/k/swig-test> go build
# github.com/krux02/swig-test
In file included from $WORK/github.com/krux02/swig-test/_obj/foo_wrap.c:194:0:
./foo.h:5:1: Fehler: unbekannter Typname: »class«
./foo.h:5:15: Fehler: expected »=«, »,«, »;«, »asm« or »__attribute__« before »{« token
/tmp/go-build724218913/github.com/krux02/swig-test/_obj/foo_wrap.c: In Funktion »_wrap_MyClass_set«:
/tmp/go-build724218913/github.com/krux02/swig-test/_obj/foo_wrap.c:225:3: Fehler: unbekannter Typname: »class«
/tmp/go-build724218913/github.com/krux02/swig-test/_obj/foo_wrap.c:226:3: Fehler: unbekannter Typname: »class«
/tmp/go-build724218913/github.com/krux02/swig-test/_obj/foo_wrap.c:229:5: Fehler: unbekannter Typname: »class«
[...]

错误很明显,swig 尝试将所有内容构建为 C 库。

要测试它,只需复制:

go get github.com/krux02/swig-test
4

3 回答 3

4

查看将 Swig 支持添加到的错误报告go build,它似乎决定如何根据文件扩展名编译 SWIG 包装器:

  • .swig文件被视为 C
  • .swigcxx文件被视为 C++

如果重命名foo.swigfoo.swigcxx,它应该使用正确的 SWIG 标志和编译器。

于 2014-01-20T02:09:45.477 回答
1

http://golang.org/cmd/go/中所述,仅当您的构建文件以 .swigcxx 结尾时,-c++ 选项才会传递给 SWIG。

于 2014-01-20T12:52:26.210 回答
0

有关使用 C++ 的 SWIG 代码示例,请参阅 Go 源代码中的 misc/swig/callback。

于 2014-01-20T20:05:50.197 回答