About Monkey 2 › Forums › Monkey 2 Programming Help › Declaring fixed-size strings.
Tagged: fixed strings
This topic contains 5 replies, has 3 voices, and was last updated by
TurkeyLurker 1 year, 6 months ago.
-
AuthorPosts
-
September 24, 2017 at 7:57 am #10787
In C, I could allocate a data buffer as follows:
char buffer[256]
How would I do this in Monkey2? I don’t mind if the GC annihilates the string after the function call. I just want a string with a max size of 256 bytes required by an api call from an external library. Right now I am spacing out 200 characters within quotes to preallocate the string; does the job, but isn’t very um… cerebral.
September 24, 2017 at 8:16 am #10788Ok, after more thought, I’ve come up with this:
[/crayon]Monkey12[crayon-5cba95336e59f221130232 inline="true" ]Local myStr:String = String.FromChars(New Int[256])myStr = get_library_path(myStr)This “appears” to work when compiled and ran, but is it a safe call to make?
September 24, 2017 at 9:06 am #10789you have the databuffer, wich you can find in some of the mx2 source.
Here’s some code I used in the past. It’s not fixed size but well you can just put a constant instead of ‘str.CStringLength’..
Now I learn that Strings can be implicitly converted to Cstrings so I won’t use it anymore but if you need fixed size It may be what you need.. If you method looks to not work so well finaly.Local mydata:=New DataBuffer( str.CStringLength ) ‘the length is in Bytes!
str.ToCString( mydata.Data,mydata.Length )September 24, 2017 at 6:05 pm #10791Thanks abakobo.
September 25, 2017 at 5:43 am #10796I recommend using a libc.char_t pointer if you need to provide a fixed sized string or string buffer. A CString may not work, as CStrings should not be modified and are subtly different.
For example, here’s roughly how monkey2 CurrentDir function wraps the libc getcwd call:
Monkey12345678910111213141516171819#Import "<libc>"externFunction getcwd:libc.char_t Ptr( buf:libc.char_t Ptr,size:Int )publicFunction CurrentDir:String()Local buf:=New char_t[PATH_MAX]getcwd( buf.Data,PATH_MAX )Local path:=String.FromCString( buf.Data )Return pathEndNot pretty, but that’s c/c++ strings for you. I recommend wrapping ‘messy’ calls like this instead of using them directly, as above.
I also recommend looking at the libc module and std filesystem for ideas on how to write C API wrappers.
September 26, 2017 at 4:51 am #10809Thanks Mark. I’ve ported the library code to use char_t on your advice. It does mess up the code a bit, but a class I am writing already wraps the library anyway so all is well.
-
AuthorPosts
You must be logged in to reply to this topic.