char* to a string in C#

后端 未结 4 2273
北恋
北恋 2021-02-14 20:07

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         


        
相关标签:
4条回答
  • 2021-02-14 20:24

    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);
    
    0 讨论(0)
  • 2021-02-14 20:30
    public static void Main(string[] args)
            {
                var charArray = new[] {'t', 'e', 's', 't'};
                fixed (char* charPointer = charArray)
                {
                    var charString = new string(charPointer);
                }
            }
    
    0 讨论(0)
  • 2021-02-14 20:36

    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.

    0 讨论(0)
  • 2021-02-14 20:37

    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

    0 讨论(0)
提交回复
热议问题