Example #1
0
func TestAllocValueOf(t *testing.T) {
	const nmax = 10000
	type Event struct {
		F   float64
		Arr [2]float64
		Sli []float64
	}
	type branch struct {
		g      reflect.Value
		c      ffi.Value
		update func()
	}
	var evt Event
	evt.Sli = make([]float64, 0)
	set_branch := func(objaddr interface{}) *branch {
		ptr := reflect.ValueOf(objaddr)
		val := reflect.Indirect(ptr)
		cval := ffi.ValueOf(val.Interface())
		var br *branch
		br = &branch{
			g: val,
			c: cval,
			update: func() {
				br.c.SetValue(br.g)
			},
		}
		return br
	}
	br := set_branch(&evt)

	for i := 0; i < nmax; i++ {
		evt.F = float64(i + 1)
		evt.Arr[0] = -evt.F
		evt.Arr[1] = -2 * evt.F
		evt.Sli = evt.Sli[:0]
		evt.Sli = append(evt.Sli, -evt.F)
		evt.Sli = append(evt.Sli, -2*evt.F)

		br.update()
		eq(t, evt.F, br.c.Field(0).Float())
		eq(t, evt.Arr[0], br.c.Field(1).Index(0).Float())
		eq(t, evt.Arr[1], br.c.Field(1).Index(1).Float())
		eq(t, evt.Sli[0], br.c.Field(2).Index(0).Float())
		eq(t, evt.Sli[1], br.c.Field(2).Index(1).Float())
	}

	for i := 0; i < nmax; i++ {
		evt.F = float64(i + 1)
		evt.Arr[0] = -evt.F
		evt.Arr[1] = -2 * evt.F
		evt.Sli[0] = -evt.F
		evt.Sli[1] = -2 * evt.F

		br.update()
		eq(t, evt.F, br.c.Field(0).Float())
		eq(t, evt.Arr[0], br.c.Field(1).Index(0).Float())
		eq(t, evt.Arr[1], br.c.Field(1).Index(1).Float())
		eq(t, evt.Sli[0], br.c.Field(2).Index(0).Float())
		eq(t, evt.Sli[1], br.c.Field(2).Index(1).Float())
	}

}
Example #2
0
func TestValueOf(t *testing.T) {
	{
		const val = 42
		for _, v := range []interface{}{
			int(val),
			int8(val),
			int16(val),
			int32(val),
			int64(val),
		} {
			eq(t, int64(val), ffi.ValueOf(v).Int())
		}
	}

	{
		const val = 42
		for _, v := range []interface{}{
			uint(val),
			uint8(val),
			uint16(val),
			uint32(val),
			uint64(val),
		} {
			eq(t, uint64(val), ffi.ValueOf(v).Uint())
		}
	}
	{
		const val = 42.0
		for _, v := range []interface{}{
			float32(val),
			float64(val),
		} {
			eq(t, float64(val), ffi.ValueOf(v).Float())
		}
	}
	{
		const val = 42
		ctyp, err := ffi.NewStructType(
			"struct_ints",
			[]ffi.Field{
				{"F1", ffi.C_int8},
				{"F2", ffi.C_int16},
				{"F3", ffi.C_int32},
				{"F4", ffi.C_int64},
			})
		if err != nil {
			t.Errorf(err.Error())
		}
		cval := ffi.New(ctyp)
		for i := 0; i < ctyp.NumField(); i++ {
			cval.Field(i).SetInt(int64(val))
			eq(t, int64(val), cval.Field(i).Int())
		}
		gval := struct {
			F1 int8
			F2 int16
			F3 int32
			F4 int64
		}{val + 1, val + 1, val + 1, val + 1}
		rval := reflect.ValueOf(gval)
		eq(t, rval.NumField(), cval.NumField())
		for i := 0; i < ctyp.NumField(); i++ {
			eq(t, rval.Field(i).Int()-1, cval.Field(i).Int())
		}
		cval = ffi.ValueOf(gval)
		for i := 0; i < ctyp.NumField(); i++ {
			eq(t, rval.Field(i).Int(), cval.Field(i).Int())
		}
	}
}