I have a C module with a unicode string like this:
I have all the bridging header and all, Swift sees the C variable, no problem with that part. However, how do I get this converted to a String in Swift? I was trying to do something like this:
Swift came back with an ugly error:
Any idea how it is done? I could not find anything useful on Google. Thanks.
Code Block wchar_t * helloWorld = L"Hello World";
I have all the bridging header and all, Swift sees the C variable, no problem with that part. However, how do I get this converted to a String in Swift? I was trying to do something like this:
Code Block let hw = String(cString: helloWorld, encoding: .unicode)
Swift came back with an ugly error:
Code Block Cannot convert value of type 'UnsafeMutablePointer<wchar_t>?' (aka 'Optional<UnsafeMutablePointer<Int32>>') to expected argument type 'UnsafePointer<CChar>' (aka 'UnsafePointer<Int8>')
Any idea how it is done? I could not find anything useful on Google. Thanks.
wchar_t is a system dependent type in C, I assume it used under the default settings of Apple's platform, meaning 32-bit wide.
Under the assumption, an L-prefixed string literal is made of Unicode Code Points, 32-bit each.
Unfortunately, Swift.String does not have an initializer taking a pointer to wchar_t.
You may need to write something like this:
Under the assumption, an L-prefixed string literal is made of Unicode Code Points, 32-bit each.
Unfortunately, Swift.String does not have an initializer taking a pointer to wchar_t.
You may need to write something like this:
Code Block let byteSize = wcslen(helloWorld) * MemoryLayout<wchar_t>.stride let data = Data(bytes: helloWorld, count: byteSize) let encoding: String.Encoding = (1.littleEndian == 1) ? .utf32LittleEndian : .utf32BigEndian let str = String(data: data, encoding: encoding)!