IT博客汇
  • 首页
  • 精华
  • 技术
  • 设计
  • 资讯
  • 扯淡
  • 权利声明
  • 登录 注册

    如何:将 System::String 转换为 wchar_t* 或 char*

    天下发表于 2015-12-01 03:08:00
    love 0
    ms-help://MS.VSCC.v90/MS.MSDNQTR.v90.chs/dv_vccore/html/385da01b-5649-4543-8076-e3e251243ff0.htm
    // convert_string_to_wchar.cpp
    // compile with: /clr
    #include < stdio.h >
    #include < stdlib.h >
    #include < vcclr.h >

    using namespace System;

    int main() {
       String ^str = "Hello";

       // Pin memory so GC can't move it while native function is called
       pin_ptr<const wchar_t> wch = PtrToStringChars(str);
       printf_s("%S\n", wch);

       // Conversion to char* :
       
    // Can just convert wchar_t* to char* using one of the 
       
    // conversion functions such as: 
       
    // WideCharToMultiByte()
       
    // wcstombs_s()
       
    //  etc
       size_t convertedChars = 0;
       size_t  sizeInBytes = ((str->Length + 1) * 2);
       errno_t err = 0;
       char    *ch = (char *)malloc(sizeInBytes);

       err = wcstombs_s(&convertedChars, 
                        ch, sizeInBytes,
                        wch, sizeInBytes);
       if (err != 0)
          printf_s("wcstombs_s  failed!\n");

        printf_s("%s\n", ch);
    }


    天下 2015-12-01 11:08 发表评论


沪ICP备19023445号-2号
友情链接