-
-
Save sayrer/034a0825ac41a6138ee379284bffbc38 to your computer and use it in GitHub Desktop.
How to pass UTF-8 strings to and from Java in SWIG
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// inefficient, but correct | |
// | |
// See also: https://docs.rs/cesu8 | |
namespace std { | |
%typemap(jni) string "jbyteArray" | |
%typemap(in) string { | |
jsize length = jenv->GetArrayLength($input); | |
char* buf = (char *) jenv->GetPrimitiveArrayCritical($input, NULL); | |
// TODO: null/error check | |
$1 = std::string(buf, length); | |
jenv->ReleasePrimitiveArrayCritical($input, buf, 0); | |
} | |
%typemap(jtype) string "byte[]" | |
%typemap(jstype) string "String" | |
%typemap(out) string { | |
const size_t len = $1.size(); | |
$result = jenv->NewByteArray(len); | |
// TODO: check that this succeeded | |
jenv->SetByteArrayRegion($result, 0, len, (const jbyte*)$1.data()); | |
} | |
%typemap(javaout) string { | |
return java.nio.charset.StandardCharsets.UTF_8.decode(java.nio.ByteBuffer.wrap($jnicall)).toString(); | |
} | |
%typemap(javain, | |
pre= "byte[] temp$javainput = $javainput.getBytes(java.nio.charset.StandardCharsets.UTF_8);" | |
) string | |
"temp$javainput" | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment