Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Converting string to pointer syntax

Tags:

c#

.net

This compiles:

string s = "my string";
unsafe 
{
    fixed (char* ptr = s)
    {               
          // do some works
    }
}

This does not:

string s = "my string";
unsafe 
{
    fixed (char* ptr = (char*)s)
    {               
          // do some works
    }
}

error CS0030: Cannot convert type 'string' to 'char*'

I cannot find the spot in the c# spec which allows the first syntax but prohibit the second. Can you help and point out where this is talked about?

like image 308
Andrew Savinykh Avatar asked Sep 24 '15 19:09

Andrew Savinykh


1 Answers

It's in section 18.6 of the spec - the fixed statement.

The relevant productions are:

fixed-statement:
  fixed ( pointer-type fixed-pointer-declarators ) embedded-statement

fixed-pointer-declarator:
   identifier = fixed-pointer-initializer

fixed-pointer-initializer:
  & variable-reference
  expression

You're trying to use the expression version. Now, while there isn't a normal "conversion as an expression* from string to char *, the spec calls out the string case, saying that a fixed-pointer-initializer can be:

An expression of type string, provided the type char* is implicitly convertible to the pointer type given in the fixed statement. In this case, the initializer computes the address of the first character in the string, and the entire string is guaranteed to remain at a fixed address for the duration of the fixed statement. The behavior of the fixed statement is implementation-defined if the string expression is null.

So although it looks like you're just performing a normal variable declaration and using an implicit conversion from string to char *, you're really making use of a special case of what the expression in a fixed-pointer-initializer is allowed to be.

like image 173
Jon Skeet Avatar answered Oct 25 '22 07:10

Jon Skeet