11

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.

method
  • 1,369
  • 3
  • 16
  • 29
  • 6
    Make sure that c points to Unicode (UTF-16) data. – Michael Liu Jan 27 '12 at 22:52
  • I'm calling a function in a native DLL which returns "hi" as a `char*`. For some reason the converted string isn't "hi". – method Jan 27 '12 at 22:59
  • 3
    You've posted nothing that can be used to help you. "I've got something (but I'm not gonna tell you what it is), and when I do this thing, it's returning something I don't expect (but I'm not telling you that either)." Post the declaration of the external function, the import statement you're using in C#, and the code calling it including variable declarations, and perhaps someone can help. As is, it's really guesswork. – Ken White Jan 27 '12 at 23:05
  • 2
    How do you receive this char*? Is it from an unmanaged (native) DLL that you're calling through P/Invoke? If that's the case, your P/Invoke declaration may be tweaked such that the framework marshaller does this for you. Keep in mind that char* in C# and char* in C/C++ are not the same: char* in C# is really wchar_t* in C++. – xxbbcc Jan 27 '12 at 23:09

4 Answers4

21

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);
Michael Liu
  • 52,147
  • 13
  • 117
  • 150
2

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.

xxbbcc
  • 16,930
  • 5
  • 50
  • 83
  • In my case, it didn't work. I had to use the Marshal answer from @michael liu. Your answer was still trying to free up the memory after and it caused issue on the type I am working on. – Nordes Mar 16 '19 at 06:26
1

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

Community
  • 1
  • 1
0
public static void Main(string[] args)
        {
            var charArray = new[] {'t', 'e', 's', 't'};
            fixed (char* charPointer = charArray)
            {
                var charString = new string(charPointer);
            }
        }
Efe ÖZYER
  • 381
  • 1
  • 5
  • 10