LoginSignup
2
3

More than 5 years have passed since last update.

JNAでC++に渡した文字列が文字化けしてしまう場合

Last updated at Posted at 2018-03-09

事例

JavaのString型をJNAでC++に渡す場合にChar*型で受け取りstd:string型に代入して扱うと文字化けしてしまう

文字コードの問題

どうやらJavaではUTF-16が使われているみたいで、今回の自分のC++の環境ではShift-JISが必要な環境だったみたいです。

C++では環境によってそれぞれの型で扱える文字コードが変わってくるみたいです。
@yumetodoさんありがとうございました。

おそらくその変換がうまくいっておらず、エラーになってしまったのではないかと推測してます。

解決策

ここの方のコードを一部引用させていただいております。
http://nekko1119.hatenablog.com/entry/2017/01/02/054629

use.cpp
#include <iostream>
#include <string>
#include <codecvt>
#include <cassert>
#include <locale>

void useString(char* str){
  std:string strUtf;
  strUtf = str;
  /* uft-8からshift-JISに変換 */
  strShiftJis = utf8_to_multi_cppapi(strUtf);
  /*こっから先は好きにしてください*/
}

std::string utf8_to_multi_cppapi(std::string const& src)
{
  auto const wide = utf8_to_wide_cppapi(src);
  return wide_to_multi_capi(wide);
}

std::string wide_to_multi_capi(std::wstring const& src)
{
  std::size_t converted{};
  std::vector<char> dest(src.size() * sizeof(wchar_t) + 1, '\0');
  if (::_wcstombs_s_l(&converted, dest.data(), dest.size(), src.data(), _TRUNCATE, ::_create_locale(LC_ALL, "jpn")) != 0) {
    throw std::system_error{ errno, std::system_category() };
  }
  return std::string(dest.begin(), dest.end());
}

std::wstring utf8_to_wide_cppapi(std::string const& src)
{
  std::wstring_convert<std::codecvt_utf8_utf16<wchar_t>> converter;
  return converter.from_bytes(src);
}

結論

文字コードのこと勉強できてよかった。

参考文献

http://marupeke296.com/CPP_charUnicodeWideChar.html
http://nekko1119.hatenablog.com/entry/2017/01/02/054629
https://cpprefjp.github.io/reference/codecvt/codecvt_utf8_utf16.html
https://theolizer.com/cpp-school1/cpp-school1-18/

2
3
4

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
2
3