A
A
Alexey2015-01-26 23:40:42
go
Alexey, 2015-01-26 23:40:42

Calling C functions with data from a Go package, is it possible?

Good afternoon.
Looked at the documentation:

  • c-go-cgo
  • cgo
  • go-sqlite3 sources

However, it is not very clear how to call a C function with data from Go. I would like to declare an array in the package:
var arr [10]int
and pass it to my function written in C:
C.MyFunc(arr, 10)
Where can I define MyFunc like this:
void MyFunc(int *arr, int len);
Can you tell me if this can be done?
-------------------------------------------------- ----------------------
compiles like this:
package libs
func MySum(arr [4]int) int {
  my_arr := unsafe.Pointer(&arr[0])
  my_len := C.int(len(arr))
  res := C.Sum1((*C.int)(my_arr), my_len)
  return int(res)
}

where Sum1:
int Sum1(int *arr, int len)
{
    std::cout << "----------  inside Sum1 (C++) ------------\n";
    int sum = 0;
    std::cout << "len=" << len << std::endl;
    for (int i=0; i<len; ++i)
    {
        std::cout << "arr[" << i << "]=" << arr[i] << std::endl;
        sum += arr[i];
    }
    std::cout << "sum=" << sum << std::endl;
    std::cout << " ----------  Sum1 (C++) end  ------------\n";
    return sum;
}

In Go I call it like this:
arr := [4]int{1, 2, 3, 4}
fmt.Println(libs.MySum(arr))

However, it does not work correctly and inside the C code instead of 1,2,3,4 I see 1,0,2,0. Apparently the dimensions of ints do not match.
-------------------------------------------------- ----
replacing int with int32 in Go code solves the issue.

Answer the question

In order to leave comments, you need to log in

1 answer(s)
A
Artem, 2015-01-27
@MAKAPOH

I think it's worth smoking towards unsafe.Pointer. Something like this: Passing arrays/slices as pointers to C functions

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question