zoukankan      html  css  js  c++  java
  • [C# Tip]How to: Convert System::String to wchar_t* or char*

    (MSDN)You can use PtrToStringChars in Vcclr.h to convert String to native wchar_t * or char *. This always returns a wide Unicode string pointer because CLR strings are internally Unicode. You can then convert from wide as shown in the following example.

    Example

    // 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);
    }

    Output

    Hello
    Hello
  • 相关阅读:
    Python之‘’控制流‘’
    Python之运算符以及基本数据类型的object
    Python第一次写的代码
    Oracle角色管理
    Oracle的控制文件和日志文件
    Oracle的权限管理
    Oracle内置函数
    Oracle视图的使用
    Oracle事务和锁
    Oracle的用户管理
  • 原文地址:https://www.cnblogs.com/taoxu0903/p/1819498.html
Copyright © 2011-2022 走看看