【问题标题】:Converting a wstring to jstring on Linux在 Linux 上将 wstring 转换为 jstring
【发布时间】:2011-11-25 17:36:23
【问题描述】:

我在 unix 中将 wstring 转换为 jstring 时遇到问题,因为 linux 上 wchar_t 的大小为 4 个字节(不像 windows 那样为 2 个字节,因此我不能使用 wchar_t 到 jchar 的转换)。

谁能帮帮我?

谢谢, 雷扎

【问题讨论】:

    标签: java c++ java-native-interface widestring


    【解决方案1】:

    您必须使用iconv() 之类的东西,因为 C++ 宽字符串具有不透明(读取:未知)编码,而 Java 需要 UTF16。试试这个:

    #include <iconv.h>
    #include <string>
    #include <vector>
    #include <iostream>
    
    std::u16string convert(std::wstring s)
    {
      iconv_t cd = iconv_open("UTF-16BE", "WCHAR_T");
    
      if (cd == iconv_t(-1))
      {
        std::cout << "Error while initializing iconv: " << errno << std::endl;
        iconv_close(cd);
        return std::u16string();
      }
    
      std::size_t n = s.length() * 2 + 1; // Each character might use up to two CUs.
      const std::size_t norig = n;
      std::size_t m = s.length() * sizeof(std::wstring::value_type);
    
      std::vector<char16_t> obuf(n);
      char * outbuf = reinterpret_cast<char*>(obuf.data());
      const char * inbuf = reinterpret_cast<const char*>(&s[0]);
    
      const std::size_t ir = iconv(cd, const_cast<char**>(&inbuf), &m, &outbuf, &n);
    
      if (ir == std::size_t(-1))
      {
        std::cout << "Error while converting with iconv(): " << errno << ":" << EINVAL << ", left " << m
                  << ", written " << std::dec << norig - n << " bytes." << std::endl;
        iconv_close(cd);
        return std::u16string();
      }
    
      iconv_close(cd);
    
      return std::u16string(obuf.data(), (norig - n)/sizeof(std::u16string::value_type));
    }
    

    如果您没有char16_tstd::u16string,您可以使用uint16_t 作为基本字符类型,并使用std::basic_string&lt;uint16_t&gt;std::vector&lt;uint16_t&gt; 作为结果容器。

    【讨论】:

    • 谢谢。所以这个方法是将 wstring 转换为 utf16 字符串,对吧?那么,我应该如何从这个 wstring 中创建一个 jstring 呢?
    • @RezaPlusPlus:input 是一个不透明的 C++ 宽字符串,而这个函数的 output 是一个定义良好的 UTF-16BE 字符串。我不知道 jstrings 是什么,但您应该能够以某种方式将指向结果的第一个元素的指针传递给 jstring。
    • 顺便说一句,std::u16string 是标准 STL 吗?
    • @RezaPlusPlus:没有所谓的“标准 STL”; “STL”是 1994 年的历史产物 :-) u16string 是 C++11 标准的一部分。如果你不支持,你可以使用uint16_ts 的向量,正如我在最后一段中建议的那样。
    • 感谢和抱歉,我错过了最后一段。
    猜你喜欢
    • 1970-01-01
    • 2012-05-16
    • 1970-01-01
    • 1970-01-01
    • 2021-11-17
    • 2015-07-12
    • 2010-09-09
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多