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 = f
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);
public static void Main(string[] args)
{
var charArray = new[] {'t', 'e', 's', 't'};
fixed (char* charPointer = charArray)
{
var charString = new string(charPointer);
}
}
Update your P/Invoke declaration of your external function as such:
[DllImport ( "MyDll.dll", CharSet = CharSet.Ansi, EntryPoint = "Func" )]
[return : MarshalAs( UnmanagedType.LPStr )]
string Func ( ... );
This way you won't have to do extra work after you get the pointer.
Your example isn't completely clear, but your comment suggests you're calling into a c++ dll from c#. You need to return a bstr, not a char * or a string.
I'd start with this question/answer, which I used when I had to perform this operation:
How to return text from Native (C++) code