在Linux上将wstring转换为jstring

时间:2011-11-25 17:36:24

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

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

有人可以帮助我吗?

谢谢, 礼

1 个答案:

答案 0 :(得分:2)

你必须使用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<uint16_t>std::vector<uint16_t>作为生成的容器