In the context of unsafe I thought people might find this interesting...
I have been looking at C# strings and its quite obvious that what they
really wanted was a value type ( for performance reasons) that is
normally passed by reference but what they didn't want was users
putting method ( ref string A) . So what they did was make it a
sealed class like this
public sealed class String
{
int length;
char charArray;
}
being a reference type it is passed by reference by default.
Note the char charArray instead of char [] charArray . ( and they
could not go string : char[] )
When the runtime creates a string it copies the data into the string (
note not ptr to an array) sets the length and sets the size of the
object (not visible to the user) , also note if length and charArray
were reversed in position it will go pop !.
Now to access the internal data the class provides these ( checks removed)
public char this[int index]
{
get
{
fixed (char* c = &start_char)
return c[index];
}
}
}
and
public char[] ToCharArray(int startIndex, int length)
{
char[] tmp = new char [length];
fixed (char* dest = tmp, src = this)
CharCopy (dest, src + startIndex, length);
return tmp;
}
The fixed is needed since its the actual data not a reference to an
array. Obviously unsafe here is used to get around some language
deficiencies but it does provide the flexibility to get the job done.
Arrays use an external call for an interface call and some compiler
magic for the array index.
Im curious why they didn't use something like typedef char[] string ,
I suspect its because they wanted it immutable and they could not
attach the string specific methods to the array type in v1 ( with
extension methods and possibly generic methods it is possible , but
that wasn't in v1 ) . Note because of this string[i] in .NET is not
fast so intensive work which does this ( or makes changes ) requires
conversion to char[].
However its a good example where unsafe allows you to do something
without adding another feature to the language eg do users really need
to create there own method of making new arrays ( or strings) when a
small bit of code in a compiler or runtime will do . Likewise is it
worth adding the feature to a language be able to write a runtime when
a bit of unsafe or worst case a handful of lines in C will do ?
Regards,
Ben
>>>>
>>>> Every other use of unsafe code that I have seen exists to correct a
>>>> deficiency of the language design, most commonly in the area of arrays vs.
>>>> vectors or in the area of low-level I/O. There are known strongly-typed
>>>> solutions for both cases.
_______________________________________________
bitc-dev mailing list
[email protected]
http://www.coyotos.org/mailman/listinfo/bitc-dev