Esempio n. 1
0
func GoToCgo(ti *gi.TypeInfo, arg0, arg1 string, flags ConvFlags) string {
	var out bytes.Buffer
	printf := PrinterTo(&out)

	switch tag := ti.Tag(); tag {
	case gi.TYPE_TAG_VOID:
		if ti.IsPointer() {
			printf("%s = unsafe.Pointer(%s)", arg1, arg0)
			break
		}
		printf("<ERROR: void>")
	case gi.TYPE_TAG_UTF8, gi.TYPE_TAG_FILENAME:
		printf("%s = _GoStringToGString(%s)", arg1, arg0)
		if flags&ConvOwnEverything == 0 {
			printf("\ndefer C.free(unsafe.Pointer(%s))", arg1)
		}
	case gi.TYPE_TAG_ARRAY:
		switch ti.ArrayType() {
		case gi.ARRAY_TYPE_C:
			var nelem string
			if ti.IsZeroTerminated() {
				nelem = fmt.Sprintf("(len(%s) + 1)", arg0)
			} else {
				nelem = fmt.Sprintf("len(%s)", arg0)
			}

			// alloc memory
			printf("%s = (%s)(C.malloc(C.size_t(int(unsafe.Sizeof(*%s)) * %s)))\n",
				arg1, CgoType(ti, TypeNone), arg1, nelem)
			printf("defer C.free(unsafe.Pointer(%s))\n", arg1)

			// convert elements
			printf("for i, e := range %s {\n", arg0)
			array := CgoArrayToGoArray(ti.ParamType(0), arg1)
			conv := GoToCgo(ti.ParamType(0), "e", array+"[i]", flags)
			printf(PrintLinesWithIndent(conv))
			printf("}")

			// write a trailing zero if necessary (TODO: buggy)
			if ti.IsZeroTerminated() {
				printf("\n%s[len(%s)] = nil", array, arg0)
			}

		}
	case gi.TYPE_TAG_GLIST:
	case gi.TYPE_TAG_GSLIST:
	case gi.TYPE_TAG_GHASH:
	case gi.TYPE_TAG_ERROR:
	case gi.TYPE_TAG_INTERFACE:
		if ti.IsPointer() {
			flags |= ConvPointer
		}
		printf(GoToCgoForInterface(ti.Interface(), arg0, arg1, flags))
	default:
		if ti.IsPointer() {
			flags |= ConvPointer
		}
		printf(GoToCgoForTag(tag, arg0, arg1, flags))
	}

	return out.String()
}