• Post Reply Bookmark Topic Watch Topic
  • New Topic
programming forums Java Mobile Certification Databases Caching Books Engineering Micro Controllers OS Languages Paradigms IDEs Build Tools Frameworks Application Servers Open Source This Site Careers Other Pie Elite all forums
this forum made possible by our volunteer staff, including ...
Marshals:
  • Campbell Ritchie
  • Tim Cooke
  • paul wheaton
  • Liutauras Vilda
  • Ron McLeod
Sheriffs:
  • Jeanne Boyarsky
  • Devaka Cooray
  • Paul Clapham
Saloon Keepers:
  • Scott Selikoff
  • Tim Holloway
  • Piet Souris
  • Mikalai Zaikin
  • Frits Walraven
Bartenders:
  • Stephan van Hulst
  • Carey Brown

JNI - return struct from C

 
Greenhorn
Posts: 6
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
Hi folks

I'm having some trouble returning a C struct to Java using JNI. Currently I'm trying to use the javolution Struct library, though the documentation seems to be lacking. I have a small struct now, but will eventually have a
struct which contains pointers to other structs, char arrays, etc.

Here's what I have:

C Code:
typedef struct {
long count;
} Results;


JNIEXPORT jobject JNICALL Java_JTest_CTest (JNIEnv *env, jobject job) {
Results results;
results.count = 42;
printf("%li\n", results.count);
return (*env)->NewDirectByteBuffer(env, &results, sizeof(Results));
}



Java code:
class TestStruct extends Struct {
Signed32 count = new Signed32();
}

class JTest {
private native TestStruct CTest();
public static void main (String args[]) {

JTest jt = new JTest();

TestStruct ts = jt.CTest();
System.out.println(ts.count);
}

static {
System.loadLibrary("CTest");
}
}

Can someone either point me in the right direction, tell me what I'm doing wrong, or maybe there is something completely different I should be doing?

TIA,
-ben
 
author and iconoclast
Posts: 24207
46
Mac OS X Eclipse IDE Chrome
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
I can't critique the whole program, as I've never used this "javalution struct library" of which you speak, but I can tell you one bad, bad thing about your native code: the argument to NewDirectByteBuffer is supposed to be a pointer to a block of memory that will be staying put; but you're passing the address of a struct on the stack, which will turn into garbage as soon as the native function returns. You need to dynamically allocate (malloc, or new) your struct, or allocate it from a static array of structs, or something -- but you can't return stack-based objects from your JNI functions any more than you can return them within normal C(++) code.
 
rubbery bacon. crispy tiny ad:
Smokeless wood heat with a rocket mass heater
https://woodheat.net
reply
    Bookmark Topic Watch Topic
  • New Topic