program-o-steve
program-o-steve

Reputation: 2678

converting jint to jstring

#include <stdio.h>
#include "Package_MyTester.h"

jstring Java_Package_MyTester_NMethod
 (JNIEnv *env, jobject obj, jint first, jint second) {
  jint result_i = first * second;
  jstring result;
  int x = 0;
  for(x=0;x<5;x++) {
      printf("%d",x);
  }

  return result;      
}

This program multiplies two jints. The result has to be in jstring. Is there a way to convert jint to jstring ?.

Upvotes: 4

Views: 5797

Answers (1)

Alnitak
Alnitak

Reputation: 339906

You need to create a C buffer containing the result (using sprintf) and then return the result of a NewStringUTF function:

jstring Java_Package_MyTester_NMethod
 (JNIEnv *env, jobject obj, jint first, jint second) {
  jint result_i = first * second;
  char buf[64]; // assumed large enough to cope with result

  sprintf(buf, "%d", result_i);  // error checking omitted

  return (*env)->NewStringUTF(env, buf);      
}

See §3.2.3 of http://java.sun.com/docs/books/jni/html/objtypes.html

Upvotes: 6

Related Questions