Search code examples
c#unsafe

Converting from string to char* only copies the first character


I have looked at most of the string to char* conversion SO answers, but it is not working for me. Here is my code:

public static void Main() {
    string name = "ELEM";
    unsafe{
          fixed(char* name_ptr = name) {
              Console.WriteLine(name_ptr->ToString());
          }
    }
} 
// Output: E

I need to do this since I have to pass a char* to my C++ custom DLL. Why would it only copy the first character only, and how can I properly convert string to a char*?


Solution

  • You get the first character only, because name_ptr is nothing but a reference to a single character and when you call name_ptr->ToString() you actually call char.ToString().

    You should use a StringBuilder instead to pass a string to a C/C++ DLL. See this question.