Question

I want to build my project with "go build". I've not found any documentation how to integrate swig with the go build process. And also very important, it should be a C++ example C is easy.

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

output

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«
[...]

the error is obvious, swig tries to build everything as a C library.

to test it, just copy:

go get github.com/krux02/swig-test
Était-ce utile?

La solution

Looking at the bug report that added Swig support to go build, it looks like it decides how to compile the SWIG wrapper based on the file extension:

  • .swig files are treated as C
  • .swigcxx files are treated as C++

If you rename foo.swig to foo.swigcxx, it should use the correct SWIG flags and compiler.

Autres conseils

As documented on http://golang.org/cmd/go/, the -c++ option will be passed to SWIG only if your build file ends with .swigcxx.

See misc/swig/callback in the Go sources for an example of SWIG code that uses C++.

Licencié sous: CC-BY-SA avec attribution
Non affilié à StackOverflow
scroll top