2

If I call a native method with the memory address and the type of data stored at that address, how can i create a pointer to that address in JNI?

In Java:

pointers(long.class, 810234092817);

In JNI:

JNIEXPORT jlong JNICALL Java_JNIFoo_pointers
    (JNIEnv *env, jobject obj, jclass cls, jlong addr) {

   // if cls is long, then i want to dynamically create the following 
   // b/c i know the data at *addr* is of type *cls*.
   // This works. 
   jlong* p = (jlong *) addr;

   // jclass has the class type and addr has the actual address. But I can't do this
   (cls*) p = (cls *) addr;
}

How can i create a pointer to jlong address of type jclass?

Praveen
  • 1,781
  • 6
  • 26
  • 32
  • This doesn't make much sense, but what sense it does make leads me to think that what is presented is an XY problem. What are you trying to accomplish by this? – John Bollinger Aug 03 '16 at 04:09
  • That's correct. `(cls*) p = (cls *) addr;` is not a thing you can do in C++, unless `cls` is a type. And you can't do it for many types all at once unless `cls` is a template parameter. – user253751 Aug 03 '16 at 04:33
  • umm...so i need to call `getName` on `cls` and do if-else and then cast `addr` accordingly? – Praveen Aug 03 '16 at 04:48
  • @JohnBollinger i simply want to be able to read data starting from that address. But in order to read, i need to know what type of data is stored. Then use the type to create the corresponding pointer to read. Does it make sense now? – Praveen Aug 03 '16 at 04:50
  • I doubt that, @Praveen. Reading the data serves no purpose by itself. If your function truly did nothing else, then a good compiler would probably optimize out the whole function body. In that case you might as well solve your problem by leaving the function body empty in the first place. – John Bollinger Aug 03 '16 at 05:00
  • @JohnBollinger I am new to JNI. I am doing this as a learning exercise. I am thinking of writing a sorting method on this array starting at that address. make sense now? – Praveen Aug 03 '16 at 05:03
  • 1
    On the other hand, if your function does something with the data after reading it, then that depends on the data type, so the compiler needs to be able to determine that statically. In that case, you might save yourself some trouble by doing what Java itself does: write a separate method for each primitive type you want to handle, and one more to handle all reference types if necesary. – John Bollinger Aug 03 '16 at 05:04
  • As you are a new JNI programmer, I urge you to start with a simpler exercise. Instead of trying to handle primitives generically -- which even Java itself does not do -- start with native methods that are built for specific types. – John Bollinger Aug 03 '16 at 05:10
  • @JohnBollinger will do. Thank you – Praveen Aug 03 '16 at 05:11

0 Answers0