How convert Pointer(UInt8) to String

458 views
Skip to first unread message

Jason Frey

unread,
Sep 5, 2017, 2:12:49 PM9/5/17
to Crystal

I am working on a C binding and one of the methods returns a LibC::Char* (which under the covers is just a Pointer(UInt8)). It’s a regular null-terminated C string. I can’t figure out how to convert that to a Crystal String, so I can do things like String comparisons. I know I can do to_slice with the length, but then I have to know the length, however I have used that to verify that the contents are the bytes I expect.

So, how do I convert a Pointer(UInt8) to a String?

Thanks,
Jason

Chris Hobbs

unread,
Sep 5, 2017, 2:15:25 PM9/5/17
to crysta...@googlegroups.com

I don’t know if you missed it, but there are actually several constructors for String which take a UInt8*. The one you want (assuming you dont have a size) is this one. There’s also this one which is safer and you should use it if the C library has given you an explicit size.

--
You received this message because you are subscribed to the Google Groups "Crystal" group.
To unsubscribe from this group and stop receiving emails from it, send an email to crystal-lang...@googlegroups.com.
To post to this group, send email to crysta...@googlegroups.com.
Visit this group at https://groups.google.com/group/crystal-lang.
To view this discussion on the web visit https://groups.google.com/d/msgid/crystal-lang/1189f977-1b7e-4218-bc83-1dbf5c161eaf%40googlegroups.com.
For more options, visit https://groups.google.com/d/optout.

Jason Frey

unread,
Sep 5, 2017, 3:28:28 PM9/5/17
to Crystal
Thank you!  I completely didn't think to look at String.new, thinking there would be something on the Pointer class and a convert_to_string or as_string method or something.

Thanks,
Jason
Reply all
Reply to author
Forward
0 new messages