tags:

views:

1663

answers:

3

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

+1  A: 

You can get byte[] array from string using Encoding.ASCII.GetBytes. This is probably convertible to char* using fixed statement in C#. (This pins the allocated memory, not allowing gc to move it - then you can make a pointer to it).

So my answer is yes only if you manage to convert byte* to char*. (in C/C++ this wouldn't be a problem, but I'm not that sure about C#)

PS> I'll post some code later if I find a bookmark to an article on this. I know I have it somewhere..

kubal5003
You should also consider Encoding.UTF8 as that will preserve all unicode characters.
asveikau
Or rather, it's better to use Encoding.Unicode (and PWSTR on the C end) if passing to a native Win32 function...
asveikau
You have to check first if those aren't multibyte(and I think that they in fact are), because this complicates it a "little bit"..
kubal5003
Funny that you should mention "fixed". Studying an assembly (using reflector) I found online an that relies on interaction with Win32 entities I saw a method that takes a string argument. The first thing that happens to the string is fixed( char* path = (char*)strargument){...}. The Char* eventually gets assigned to a win32 struct (WINTRUST_FILE_INFO.LPCWSTR parameter). Trying this for myself for educational purposes does not work (compiler says "cannot convert string to char*") I do not understand why is this compiler generated, did the orig. code assign the string directly to the struct?
Kris
Did some more research... it appears that it is valid in C# to just do something like: string test = "test"; fixed (char* p = test){..}. The thing that threw me of is that the compiler uglies this up by generating: private static unsafe void Main() { string test = "test"; fixed (char* CS$519$0000 = ((char*) test)) { char* p = CS$519$0000; } }Which made me thing I would need to be able to find ways to convert string to char* Who'd have thought it would be as simple as char* = string;
Kris
The thing that set me on the right track is: http://msdn.microsoft.com/en-us/library/f58wzh21%28VS.80%29.aspx
Kris
+7  A: 

You can pass a StringBuilder as a char*

Have a look at http://pinvoke.net to see if the signature for the function is not already there.

Geoff
+1, Or just `string` if it is an input only parameter.
sixlettervariables
I am awarding this answer since you basically answered my question but it seems that, at least for what I was doing all that was needed was fixed(char* s = string){...}
Kris
+3  A: 

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.

Heinzi