Passing NULL to a C function

I am new to GoLang and writing a C-GO binding.

The C Function takes an argument which is a const char *. This works fine if I pass NULL for the argument in C.

Now in my GO implementation I need to pass NULL in the C call.

func AvformatMyfunc(ctx **Context, o *OutputFormat, fo, fi string) int {
	Cformat_name := C.CString(fo)
	defer C.free(unsafe.Pointer(Cformat_name))

	Cfilename := C.CString(fi)
	defer C.free(unsafe.Pointer(Cfilename))

	return int(C.myfunc((**C.struct_AVFormatContext)(unsafe.Pointer(ctx)), (*C.struct_AVOutputFormat)(o),  Cformat_name, Cfilename))
}

This is how I am calling it in my main package.

if AvformatMyfunc(&ofmt_ctx, nil, "", os.Args[2]) != 0 {
		fmt.Printf("Unable to open output file %s\n", os.Args[2]);
		os.Exit(1);
	}

The code I have pasted above passes empty string and my c code fails. It expects NULL or some valid string to be passed as an argument. Can you please suggest how?
Thanking you in advance

Go can’t have null strings. If you’re OK with an empty string always being a null C pointer, you could do this:

func AvformatMyfunc(ctx **Context, o *OutputFormat, fo, fi string) int {
	var Cformat_name *C.char
	if fo != "" {
		Cformat_name = C.CString(fo)
		defer C.free(unsafe.Pointer(Cformat_name))
	}

	var Cfilename *C.char
        if fi != "" {
                Cfilename = C.CString(fi)
        	defer C.free(unsafe.Pointer(Cfilename))
        }
	return int(C.myfunc((**C.struct_AVFormatContext)(unsafe.Pointer(ctx)), (*C.struct_AVOutputFormat)(o),  Cformat_name, Cfilename))
}

No. Need to pass NULL only not empty string.

I solved it using *(C.char)(nil)

This topic was automatically closed 90 days after the last reply. New replies are no longer allowed.