Help in sys package related to I/O operation

As I want to access some lower-level API to do I/O operation using CreateFile function
syscall.CreateFile( name *uint16…)
While doing so I face a problem that the name parameter is of *uint16 but it should be an array ([]uint16) so that it can handle the string in the UTF-16 format. As we can see in the example provided by Microsoft -> link where TEXTmacro convert the string into wchar_t array or we can say []uint16.

Thanks in advance and sorry if I said anything wrong as I’m just a toddler in this field.

Low-level unsafe APIs like this can be tricky to get right. I’m curious why you, as a self-proclaimed toddler in the field, are trying to use them in the first place? :slight_smile:

To use these low-level APIs, I think you have to use the unsafe package and write Go code similar to this C code: https://gist.github.com/xebecnan/6d070c93fb69f40c3673

As I’m writing a blog on How to write a multi-threaded copy program in GoLang that’s why I’m doing so. I want to compare the performance of various ways to implement the copy operation. Like io.copy, os.readfile, and last with low-level API which is OS depended.

I’m able to run the program the main issue is that I can’t pass the proper name of the file as the function is only accepting the single UTF-16 character and I want to send an array

When you have a []utf16 file name, you need to pass it like &fileName[0]. In C, arrays “decay” into pointers. In Go, you have to do it manually.

1 Like

Thanks, sir great help.

I don’t understand.

This is a well-known issue, it has already been solved. Why not use the official Go solution to provide name *uint16?

Package windows

import "golang.org/x/sys/windows"

func CreateFile

func CreateFile(name *uint16, access uint32, mode uint32, sa *SecurityAttributes, createmode uint32, attrs uint32, templatefile Handle) (handle Handle, err error)

func UTF16PtrFromString

func UTF16PtrFromString(s string) (*uint16, error)

UTF16PtrFromString returns pointer to the UTF-16 encoding of the UTF-8 string s, with a terminating NUL added. If s contains a NUL byte at any location, it returns (nil, syscall.EINVAL).

Why not use the official Go solution?

Package windows

import "golang.org/x/sys/windows"

The official Go solution:

Package windows

import "golang.org/x/sys/windows"

func UTF16PtrFromString

func UTF16PtrFromString(s string) (*uint16, error)

UTF16PtrFromString returns pointer to the UTF-16 encoding of the UTF-8 string s, with a terminating NUL added. If s contains a NUL byte at any location, it returns (nil, syscall.EINVAL).

Ah, there it is! I used to know about this but forgot! :man_facepalming:

Thanks, I’m just a beginner in Go and unaware of this scenario :sweat_smile:. thanks for pointing out my mistake.

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