Returning a string from PInvoke?

Possible duplicate:
Marshal char * "in C #

I use PInvoke for the interaction between Native Code (C ++) and managed code (C #). I am just writing a simple function that gets a string from C ++ code. My code looks like this: C # code:

        [DllImport("MyDll.dll")]
        private static extern string GetSomeText();
        public static string GetAllValidProjects()
        {
            string s = GetSomeText();
            return s;
        }

C ++ code

char* GetSomeText()    
{
std::string stri= "Some Text Here";
char * pchr = (char *)stri.c_str();
return pchr;
} 

Everything works fine at the end of C ++, i.e. pchr contians "Some Text Here", but in C # line s contains a note in it. I do not know what I am doing wrong. Any help would be appreciated

+5
source share
4 answers

, , ++ . stri. stri , , .

, , . ++, # .

, .

# ++, . # StringBuilder . StringBuilder ++, - LPWSTR. # , ++ C, .

BSTR ++, ++ #.

, BSTR, . :

++

#include <comutil.h>
BSTR GetSomeText()
{
    return ::SysAllocString(L"Greetings from the native world!");
}

#

[DllImport(@"test.dll", CallingConvention = CallingConvention.Cdecl)]
[return: MarshalAs(UnmanagedType.BStr)]
private static extern string GetSomeText();

. , P/Invoke , , . , , ?

1 , , , . , , .

1 , , (, , ). 2, BSTR.

BSTR, , UTF-16, char*, " - ".

, char* BSTR :

BSTR ANSItoBSTR(char* input)
{
    BSTR result = NULL;
    int lenA = lstrlenA(input);
    int lenW = ::MultiByteToWideChar(CP_ACP, 0, input, lenA, NULL, 0);
    if (lenW > 0)
    {
        result = ::SysAllocStringLen(0, lenW);
        ::MultiByteToWideChar(CP_ACP, 0, input, lenA, result, lenW);
    } 
    return result;
}

, BSTR LPWSTR, std::string, std::wrstring ..

+14

,

std::string stri= "Some Text Here";

- , GetSomeText(). , pchr , , .

, .
++ :

char* GetSomeText()    
{
   std::string stri = "Some Text Here";
   return strcpy(new char[stri.size()], stri.c_str());
}

- . ...

0

++. , dll ++. DllImport IntPtr . , Ptr String.

[DllImport("MyDll.dll")]
private static extern IntPtr GetSomeText();
public static string GetAllValidProjects()
{
    string s = Marshal.PtrToStringAnsi(GetSomeText());
    return s;
}

: . "Some Text Here" , , , . . , Marshal.PtrToStringAnsi . IntPtr.

char* GetSomeText()    
{
    std::string stri= "Some Text Here"; 
    char * pchr = (char *)stri.c_str();
    return pchr;
} 
-1

GetSomeText() char, , u , .

[DllImport("MyDll.dll")]
private static extern string GetSomeText();
public static string GetAllValidProjects()
{
    string s = new string(GetSomeText());
    return s;
}

, char *

-3

All Articles