Alex Rivera | Logout

char* pointer from string in C#

Asked 2009-11-01T20:49:29.863
41

Is it possible to get a char* for a string variable in C#?

I need to convert a path string to a char* for using some native win32 function ...

Edit
Report

2 Answers

63

Well you could certainly do this:

string str = "my string";

unsafe 
{
    fixed (char* p = str)
    {               
        // do some work
    }
}

where there is an operator (char*) bound to the string object. However, the output format may not be compatible with the underlying C or other format... this is however quite a good solution to parse the string. Hope it's helpful for anybody who reads this post.

answered 2010-11-21T15:06:22.723
5

That depends on what you want to do. When you call a Win32 function via PInvoke, you should be able to just pass the String variable; the framework marshals everything for you. If you need something more complicated, have a look at Marshal.StringToHGlobalAnsi and other methods of the Marshal class.

answered 2009-11-01T20:55:22.157

Your Answer