Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

char* to a string in C#

Tags:

c#

pointers

I'm calling a function from a native DLL which returns a char* pointer, how can I convert the returned pointer to a string ? I tried :

char* c = function();
string s = new string(c);

But it just returned a weird Chinese character, which isn't the right value for c.

like image 690
method Avatar asked Jan 27 '12 22:01

method


People also ask

Can you convert char * to string?

We can convert a char to a string object in java by using the Character. toString() method.

Is char * A string in C?

This last part of the definition is important: all C-strings are char arrays, but not all char arrays are c-strings. C-strings of this form are called “string literals“: const char * str = "This is a string literal.

Is char * a string?

char is a primitive data type whereas String is a class in java. char represents a single character whereas String can have zero or more characters. So String is an array of chars.

What does char * mean in C?

In C, char* means a pointer to a character. Strings are an array of characters eliminated by the null character in C.


1 Answers

Perhaps the native DLL is actually returning an ANSI string instead of a Unicode string. In that case, call Marshal.PtrToStringAnsi:

using System.Runtime.InteropServices;
...
string s = Marshal.PtrToStringAnsi((IntPtr)c);
like image 171
Michael Liu Avatar answered Nov 04 '22 09:11

Michael Liu