Declaring fixed-size strings.

About Monkey 2 Forums Monkey 2 Programming Help Declaring fixed-size strings.

Tagged: 

This topic contains 5 replies, has 3 voices, and was last updated by  TurkeyLurker 1 year, 6 months ago.

Viewing 6 posts - 1 through 6 (of 6 total)
  • Author
    Posts
  • #10787

    TurkeyLurker
    Participant

    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. 🙂

    #10788

    TurkeyLurker
    Participant

    Ok, after more thought, I’ve come up with this:

    [/crayon]

    This “appears” to work when compiled and ran, but is it a safe call to make?

    #10789

    abakobo
    Participant

    you 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 )

    #10791

    TurkeyLurker
    Participant

    Thanks abakobo.

    #10796

    Mark Sibly
    Keymaster

    I 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:

    Not 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.

    #10809

    TurkeyLurker
    Participant

    Thanks 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.

Viewing 6 posts - 1 through 6 (of 6 total)

You must be logged in to reply to this topic.