Imme22009
Imme22009

Reputation: 4129

JNI Java from C++ ; Print to output?

Im using JNI to call some Java code in a C++ program. I need to print some text from Java to C++ stdout.

How can I do it?

I try: System.out.println("sdf"); in java, nothing appears.

Please , help :D

Upvotes: 0

Views: 9795

Answers (3)

Tom Blodget
Tom Blodget

Reputation: 20802

Since you didn't specify a character set and encoding, the native method should be dealing with what Java determines to be the platform default. Otherwise, it'll just be coincidence that "You win 100€" isn't printed like "You win 100Ⴌ"

So, declare it like:

    public static native void println(final byte[] stringBytes);

Call it like:

    Natives.println("You win 100€".getBytes()); // platforms default character set/encoding

And implement it like:

extern "C" JNIEXPORT void JNICALL Java_Natives_println(JNIEnv *env, jclass, jbyteArray stringBytes)
{
    auto bytes  = (env->GetByteArrayElements(stringBytes, 0)); // is_copy is not used
    auto str = reinterpret_cast<const char *>(bytes);
    std::cout << str << std::endl;
    env->ReleaseByteArrayElements(stringBytes, bytes, JNI_ABORT);  // no need to copy back
}

If you do know a specific character set/encoding (aka "code page") that you want, you can pass a Charset to String.getBytes

Upvotes: 1

Brandon
Brandon

Reputation: 23510

public class Natives {
    public static native void printf(final String WhatToPrintHere);
}

public class Main {
    public static void main(String args[]) {
        Natives.printf("Testing printing from Java");
    }
}


extern "C" JNIEXPORT void Java_Natives_printf(JNIEnv* env, jobject obj, jstring WhatToPrintHere)
{
    const char* Str = env->GetStringUTFChars(WhatToPrintHere, 0);

    std::cout<< Str <<"\n";

    env->ReleaseStringUTFChars(WhatToPrintHere, Str);
}

Upvotes: 5

SHR
SHR

Reputation: 8313

You can try call printf via JNI like this: (from wiki )

JNIEXPORT void JNICALL Java_ClassName_MethodName
        (JNIEnv *env, jobject obj, jstring javaString) {
    // printf("%s", javaString);        // INCORRECT: Could crash VM!

    // Correct way: Create and release native string from Java string
    const char *nativeString = (*env)->GetStringUTFChars(env, javaString, 0);
    printf("%s", nativeString);
    (*env)->ReleaseStringUTFChars(env, javaString, nativeString);
}

Upvotes: 3

Related Questions