1
0
mirror of https://github.com/golang/go synced 2024-11-23 07:50:05 -07:00

cmd/cgo: make the char * pointer in GoString const

This makes it more convenient for C code to use GoString with string
constants.  Since Go string values are immutable, the const qualifier is
appropriate in C.

Change-Id: I5fb3cdce2ce5079f1f0467a1544bb3a1eb27b811
Reviewed-on: https://go-review.googlesource.com/17067
Run-TryBot: Ian Lance Taylor <iant@golang.org>
TryBot-Result: Gobot Gobot <gobot@golang.org>
Reviewed-by: Russ Cox <rsc@golang.org>
This commit is contained in:
Ian Lance Taylor 2015-11-19 17:03:01 -08:00
parent 4d6a69f227
commit 17360accab
4 changed files with 27 additions and 1 deletions

View File

@ -12,6 +12,7 @@ void callPanic(void);
int callGoReturnVal(void);
int returnAfterGrow(void);
int returnAfterGrowFromGo(void);
void callGoWithString(void);
*/
import "C"
@ -276,6 +277,22 @@ func goReturnVal() (r C.int) {
return
}
// Test that C can pass in a Go string from a string constant.
func testCallGoWithString(t *testing.T) {
C.callGoWithString()
want := "string passed from C to Go"
if stringFromGo != want {
t.Errorf("string passed through C is %s, want %s", stringFromGo, want)
}
}
var stringFromGo string
//export goWithString
func goWithString(s string) {
stringFromGo = s
}
func testCallbackStack(t *testing.T) {
// Make cgo call and callback with different amount of stack stack available.
// We do not do any explicit checks, just ensure that it does not crash.

View File

@ -2,6 +2,7 @@
// Use of this source code is governed by a BSD-style
// license that can be found in the LICENSE file.
#include <string.h>
#include <sys/types.h>
#include <unistd.h>
#include "_cgo_export.h"
@ -80,3 +81,10 @@ returnAfterGrowFromGo(void)
return goReturnVal();
}
void
callGoWithString(void)
{
extern void goWithString(GoString);
const char *str = "string passed from C to Go";
goWithString((GoString){str, strlen(str)});
}

View File

@ -68,5 +68,6 @@ func Test10303(t *testing.T) { test10303(t, 10) }
func Test11925(t *testing.T) { test11925(t) }
func Test12030(t *testing.T) { test12030(t) }
func TestGCC68255(t *testing.T) { testGCC68255(t) }
func TestCallGoWithString(t *testing.T) { testCallGoWithString(t) }
func BenchmarkCgoCall(b *testing.B) { benchCgoCall(b) }

View File

@ -1429,7 +1429,7 @@ typedef __complex double GoComplex128;
*/
typedef char _check_for_GOINTBITS_bit_pointer_matching_GoInt[sizeof(void*)==GOINTBITS/8 ? 1:-1];
typedef struct { char *p; GoInt n; } GoString;
typedef struct { const char *p; GoInt n; } GoString;
typedef void *GoMap;
typedef void *GoChan;
typedef struct { void *t; void *v; } GoInterface;