Char * for string in C #

I call a function from my native DLL that 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 he just returned a strange Chinese character, which is not the correct value for c .

+4
source share
3 answers

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

 using System.Runtime.InteropServices; ... string s = Marshal.PtrToStringAnsi((IntPtr)c); 
+9
source

Update the 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 do not have to do extra work after getting the pointer.

+2
source

Your example is not entirely clear, but your comment suggests that you are calling a C ++ dll from C #. You need to return bstr, not char * or a string.

I would start with this question / answer, which I used when I needed to perform this operation:

How to return text from Native (C ++) code

+1
source

Source: https://habr.com/ru/post/1393457/


All Articles