문제

누군가 변환 할 간단한 코드를 게시 할 수 있습니까?

System::String^

에게,

C ++ std::string

즉, 나는 단지 값을 할당하고 싶습니다.

String^ originalString;

에게,

std::string newString;
도움이 되었습니까?

해결책

체크 아웃 System::Runtime::InteropServices::Marshal::StringToCoTaskMemUni() 그리고 친구들.

죄송합니다. 지금 코드를 게시 할 수 없습니다. 게시하기 전에 컴파일을 확인하기 위해이 컴퓨터의 대 VS가 없습니다.

다른 팁

나만의 굴리지 마십시오 이것들 Microsoft가 제공하는 편리한 (및 확장 가능한) 포장지.

예를 들어:

#include <msclr\marshal_cppstd.h>

System::String^ managed = "test";
std::string unmanaged = msclr::interop::marshal_as<std::string>(managed);

다음과 같이 쉽게이 작업을 수행 할 수 있습니다

#include <msclr/marshal_cppstd.h>

System::String^ xyz="Hi boys"; 

std::string converted_xyz=msclr::interop::marshal_as< std::string >( xyz);

이것은 나를 위해 효과가있었습니다.

#include <stdlib.h>
#include <string.h>
#include <msclr\marshal_cppstd.h>
//..
using namespace msclr::interop;
//..
System::String^ clrString = (TextoDeBoton);
std::string stdString = marshal_as<std::string>(clrString); //String^ to std
//System::String^ myString = marshal_as<System::String^>(MyBasicStirng); //std to String^
prueba.CopyInfo(stdString); //MyMethod
//..
//Where: String^ = TextoDeBoton;
//and stdString is a "normal" string;

C ++/CLI 프로젝트를 위해 몇 년 전에 쓴 전환 루틴은 다음과 같습니다. ~해야 한다 여전히 작동합니다.

void StringToStlWString ( System::String const^ s, std::wstring& os)
    {
        String^ string = const_cast<String^>(s);
        const wchar_t* chars = reinterpret_cast<const wchar_t*>((Marshal::StringToHGlobalUni(string)).ToPointer());
        os = chars;
        Marshal::FreeHGlobal(IntPtr((void*)chars));

    }
    System::String^ StlWStringToString (std::wstring const& os) {
        String^ str = gcnew String(os.c_str());
        //String^ str = gcnew String("");
        return str;
    }

    System::String^ WPtrToString(wchar_t const* pData, int length) {
        if (length == 0) {
            //use null termination
            length = wcslen(pData);
            if (length == 0) {
                System::String^ ret = "";
                return ret;
            }
        }

        System::IntPtr bfr = System::IntPtr(const_cast<wchar_t*>(pData));
        System::String^ ret = System::Runtime::InteropServices::Marshal::PtrToStringUni(bfr, length);
        return ret;
    }

    void Utf8ToStlWString(char const* pUtfString, std::wstring& stlString) {
        //wchar_t* pString;
        MAKE_WIDEPTR_FROMUTF8(pString, pUtfString);
        stlString = pString;
    }

    void Utf8ToStlWStringN(char const* pUtfString, std::wstring& stlString, ULONG length) {
        //wchar_t* pString;
        MAKE_WIDEPTR_FROMUTF8N(pString, pUtfString, length);
        stlString = pString;
    }

Windows Form Listbox Tostring 값을 표준 문자열로 변환하여 FSTREAM과 함께 TXT 파일로 출력 할 수 있도록 몇 시간을 보냈습니다. 내 Visual Studio에는 내가 찾은 몇 가지 답변이 사용했던 Marshal 헤더 파일이 포함되어 있지 않았습니다. 많은 시행 착오 후 마침내 System :: Runtime :: interopservices를 사용하는 문제에 대한 해결책을 찾았습니다.

void MarshalString ( String ^ s, string& os ) {
   using namespace Runtime::InteropServices;
   const char* chars = 
      (const char*)(Marshal::StringToHGlobalAnsi(s)).ToPointer();
   os = chars;
   Marshal::FreeHGlobal(IntPtr((void*)chars));
}

//this is the code to use the function:
scheduleBox->SetSelected(0,true);
string a = "test";
String ^ c = gcnew String(scheduleBox->SelectedItem->ToString());
MarshalString(c, a);
filestream << a;

예제와 함께 MSDN 페이지가 있습니다.http://msdn.microsoft.com/en-us/library/1b4az623(v=vs.80).aspx

나는 그것이 매우 간단한 솔루션이라는 것을 알고 있지만 이것은 몇 시간의 문제 해결과 여러 포럼을 방문하여 마침내 효과가있는 것을 찾았습니다.

문자열에서 std :: 문자열을 얻는 쉬운 방법을 찾았습니다^는 sprintf ()를 사용하는 것입니다.

char cStr[50] = { 0 };
String^ clrString = "Hello";
if (clrString->Length < sizeof(cStr))
  sprintf(cStr, "%s", clrString);
std::string stlString(cStr);

원수 기능을 호출 할 필요가 없습니다!

업데이트 Eric 덕분에 버퍼 오버플로를 방지하기 위해 입력 문자열의 크기를 확인하기 위해 샘플 코드를 수정했습니다.

C#은 문자열에 UTF16 형식을 사용합니다.
따라서 유형을 변환하는 것 외에도 문자열의 실제 형식에 대해서도 의식해야합니다.

컴파일 할 때 다중 바이트 문자 세트 Visual Studio와 Win API는 UTF8을 가정합니다 (실제로 Windows 인코딩은 Windows-28591 ).
컴파일 할 때 유니 코드 문자 세트 Visual Studio와 Win API는 UTF16을 가정합니다.

따라서 문자열을 UTF16에서 UTF8 형식으로 변환해야하며 STD :: 문자열로 변환해야합니다.
일부 비 라틴어 언어와 같은 다중 특성 형식으로 작업 할 때는 이것이 필요합니다.

아이디어는 그것을 결정하는 것입니다 std::wstring 언제나 대표합니다 UTF16.
그리고 std::string 언제나 대표합니다 UTF8.

이것은 컴파일러에 의해 시행되지 않으며, 좋은 정책입니다.

#include "stdafx.h"
#include <string>
#include <codecvt>
#include <msclr\marshal_cppstd.h>

using namespace System;

int main(array<System::String ^> ^args)
{
    System::String^ managedString = "test";

    msclr::interop::marshal_context context;

    //Actual format is UTF16, so represent as wstring
    std::wstring utf16NativeString = context.marshal_as<std::wstring>(managedString); 

    //C++11 format converter
    std::wstring_convert<std::codecvt_utf8_utf16<wchar_t>> convert;

    //convert to UTF8 and std::string
    std::string utf8NativeString = convert.to_bytes(utf16NativeString);

    return 0;
}

또는 더 컴팩트 한 구문으로하십시오.

int main(array<System::String ^> ^args)
{
    System::String^ managedString = "test";

    msclr::interop::marshal_context context;
    std::wstring_convert<std::codecvt_utf8_utf16<wchar_t>> convert;

    std::string utf8NativeString = convert.to_bytes(context.marshal_as<std::wstring>(managedString));

    return 0;
}

나는 마샬러에서 멀리 떨어져있는 것을 좋아합니다.

Using CString newString(originalString);

나에게 훨씬 깨끗하고 빠른 것 같습니다. 컨텍스트를 작성하고 삭제하는 것에 대해 걱정할 필요가 없습니다.

// vs2012를 사용하여 아래 코드를 작성했습니다- convert_system_string to Standard_sting

        #include "stdafx.h"
        #include <iostream>
        #include <string> 

        using namespace System;
        using namespace Runtime::InteropServices; 


        void MarshalString ( String^ s, std::string& outputstring )
        {  
           const char* kPtoC =  (const char*) (Marshal::StringToHGlobalAnsi(s)).ToPointer();                                                        
           outputstring = kPtoC;  
           Marshal::FreeHGlobal(IntPtr((void*)kPtoC));  
        }   

        int _tmain(int argc, _TCHAR* argv[])
        {
             std::string strNativeString;  
             String ^ strManagedString = "Temp";

             MarshalString(strManagedString, strNativeString);  
             std::cout << strNativeString << std::endl; 

             return 0;
        }
라이센스 : CC-BY-SA ~와 함께 속성
제휴하지 않습니다 StackOverflow
scroll top