转到:导入和C库之间的类型冲突

Trying to get acquainted with Go/C interop, I want to use git2go/libgit2 to read data of a git repository using a Redis backend.

So I came up with this code (stripped of error handling etc), which outputs a compile error that I cannot place:

./git.go:30: cannot use odbBackendC (type *C.struct_git_odb_backend) as type *git.C.struct_git_odb_backend in argument to git.NewOdbBackendFromC

Apparently the compiler thinks that git.C.struct_git_odb_backend and C.struct_git_odb_backend are different types although they're the same - only one libgit2 on the system after all. What can I do to resolve this?

Here's the full listing:

package main

/*
#cgo LDFLAGS: -L ./libgit2-backends/redis -lgit2 -lhiredis -lgit2-redis

#include <git2.h>

extern int git_odb_backend_hiredis(git_odb_backend **backend_out, const char* prefix, const char* path, const char *host, int port, char* password);
extern int git_refdb_backend_hiredis(git_refdb_backend **backend_out, const char* prefix, const char* path, const char *host, int port, char* password);

*/
import "C"

import (
  git "gopkg.in/libgit2/git2go.v23"
)

func ImportRepo(url string) {
  odb, err := git.NewOdb();

  var odbBackendC *C.git_odb_backend = nil
  C.git_odb_backend_hiredis(&odbBackendC, C.CString("prefix_"), C.CString("path"), C.CString("localhost"), 6379, C.CString(""))
  backend := git.NewOdbBackendFromC(odbBackendC)
  odb.AddBackend(backend)
}

I had the same issue when trying to split git2go into sub-packages. As far as I can tell, this is the Go compiler trying to use Go scoping rules to C code. I see two ways to work around this:

  1. Implement the git_odb interface in git2go so you can run arbitrary Go code; or
  2. Write the code that adds the backend in C and call that from your Go code