how to pass c array to golang efficiently

145 views
Skip to first unread message

hui zhang

unread,
Aug 6, 2019, 9:11:32 AM8/6/19
to golang-nuts
I build go as a so called by c program
how implement this Send function to make c  short array to be used in go as []int16 efficiently
of course ,  I can assign it one by one , but it is not an efficient way
package main

import "C"
import "fmt"

//export Summ
func Summ(x, y int) int {
return x + y
}

//export Hello
func Hello(str string) {
fmt.Printf("Hello: %s\n", str)
}

//export Send
func Send(confid string, len int, pcm *C.short) {
//put c.short array to int16 slice/array efficiently , how ?
// memcopy ?
}

func main() {
// We need the main function to make possible
// CGO compiler to compile the package as C shared/archive library
}

go build -buildmode=c-shared -o ws.so ws.go

#include <stdio.h>
#include "ws.h"

int main()
{
printf("This is exptest application.\n");
GoString str = {"Hi JXES", 7};
Hello(str);
printf("sum: %lld\n", Summ(2, 3));

short a[] = {1,2,3,4,5,6};
Send(str,6,a);
return 0;
}

gcc -o cms cms.c ws.so



Jan Mercl

unread,
Aug 6, 2019, 10:02:22 AM8/6/19
to hui zhang, golang-nuts
On Tue, Aug 6, 2019 at 11:11 AM hui zhang <fastf...@gmail.com> wrote:

Please always send code to the ML as plain, black on white text.
And/or use play.golang.org. Thanks.

Jan Mercl

unread,
Aug 7, 2019, 8:21:03 AM8/7/19
to hui zhang, golang-nuts
On Wed, Aug 7, 2019 at 3:17 AM hui zhang <fastf...@gmail.com> wrote:

> //export Send
> func Send(confid string, len int, pcm *C.short) {
> //put c.short array to int16 slice/array efficiently , how ?
> // memcopy ?
> }

s := (*[^uint(0) >> 1]int16)(unsafe.Pointer(pcm))[:len] // s is
[]int16, len(s) = len

hui zhang

unread,
Aug 7, 2019, 9:14:35 AM8/7/19
to Jan Mercl, golang-nuts
Got it, thanks!

Jan Mercl <0xj...@gmail.com> 于2019年8月7日周三 下午4:20写道:

Bryan Mills

unread,
Aug 8, 2019, 5:26:27 PM8/8/19
to golang-nuts
That constant doesn't always work. (See https://golang.org/issue/13656#issuecomment-165858089.)

If you have a static upper bound on the size of the array, then it's fine to use whatever that bound is, but if you don't then you generally need a more dynamic calculation (like the one in https://golang.org/issue/13656#issuecomment-303216308).
Reply all
Reply to author
Forward
0 new messages