In JNI, is there a more portable way than jlong to encapsulate a pointer?

Viewed 1388

I've seen examples of using a long/jlong to allow a Java object to hold onto a C++ pointer:

class Foo {
    private native long create();
}

struct Foo { };

JNIEXPORT jlong JNICALL Java_Foo_create
  (JNIEnv *, jobject)
{
    return (jlong) (new Foo);
}

This makes me feel just a little bit nervous because it assumes that a pointer will fit in 64 bits; that is untrue for example on OS/400.

Is there a safer solution, for example a Java standard library class that encapsulates a C++ pointer?

4 Answers

Not really a solution, but compile-time check can help:

static_assert(sizeof(void*) <= sizeof(jlong), "Unsupported architecture");
Related