duanrong0738
2017-11-02 12:08
浏览 209
已采纳

如何使用切片作为参数从Go调用Rust函数?

I want to call some external functions written in Rust from Go with a reference to a slice.

I have the following Rust code:

extern crate libc;

#[no_mangle]
pub extern "C" fn callme(data: &mut [libc::c_double]) -> i32 {
    data.len() as i32
}

This function is made available for the cgo compiler through this C-style header file:

#IFNDEF BOGUSLIB_H
#DEFINE BOGUSLIB_H

extern int callme(double* data);    

#ENDIF

I can now call this function from Go with the Rust crate compiled as a cdylib:

//#cgo CFLAGS: -Ipath/to/libfolder
//#cgo LDFLAGS: -Lpath/to/libfolder -lboguslib
//#include <boguslib.h>
import "C"
import (
   "unsafe"
   . "fmt"  
)

func CallmeExternal() {
   data := make([]float64, 1, 1)
   data[0] = 1.0
   ptr := (*C.double)(unsafe.Pointer(&data[0]))
   size := C.callme(ptr)

   printf("size %v",size)
}

The Go code uses the unsafe pointer trick to access the backing array, since a slice is defined as follows

type Slice struct {
   data *byte
   uint32 len
   uint32 cap
}

When I execute the code above, the length of the passed reference is incredibly large. How do I access the actual data, and what is at this moment being returned?

  • 写回答
  • 好问题 提建议
  • 追加酬金
  • 关注问题
  • 邀请回答

1条回答 默认 最新

相关推荐 更多相似问题