3 messages in net.java.dev.jna.usersRe: [jna-users] passing in a struct c...
FromSent OnAttachments
bb...@cox.netJul 10, 2007 11:19 am 
Timothy WallJul 10, 2007 5:10 pm 
bb...@cox.netJul 11, 2007 5:50 am 
Actions with this message:
Paste this link in email or IM:
Paste this link in email or IM:
Atom feed for this thread
Paste this URL into your reader:
Subject:Re: [jna-users] passing in a struct containing a null pointer?Actions...
From:bb...@cox.net (bb@cox.net)
Date:Jul 11, 2007 5:50:12 am
List:net.java.dev.jna.users

Okay, thanks, I'd missed the Memory class, and without knowing about it was not
seeing how to allocate things before the call. So this C code struct CS { unsigned char *bPointer; long *iPointer; } struct CS cs; cs.bPointer = new unsigned char[len]; cs.bPointer[0] = '\0'; cs.iPointer = 0; int rv = f(cs); might become this Java public class S extends Structure { public Pointer bPointer; public Pointer iPointer; public S(int len) { s.bPointer = new Memory(len); s.iPointer .???(null); // Do I just leave IPointer alone? Or...? allocateMemory(); // Am I letting it calculate the size, or do
I // have to say
"allocateMemory(8);" to make // an S be big enough for
two pointers? } } S s = new S(len);

I could not find any setByteArray(), so I assume you meant something like the
following to let the caller give meaningful values to allocated memory before the call to
f(): b = s.bPointer.getByteArray(0,len); b[0] = '\0'; int rv = lib.INSTANCE.f(s);

- Ben ---- Timothy Wall <twal@dev.java.net> wrote:

On Jul 10, 2007, at 2:19 PM, <bb@cox.net> <bb@cox.net> wrote:

I'm having trouble passing a struct to a library function.

The C declaration for S is: struct CS { unsigned char *barray; long *iarray; }

This is a structure containing two pointers, not two arrays. Java arrays are always interpreted as being inline in the structure, so if you want a pointer, use a Pointer. Structure doesn't currently support ByteBuffer as a structure member, so you'll need to create a Memory object of the appropriate size and call setByteArray on it for the first field and use a null value for the second.

I need (at least for now) to be able to write Java that looks like the following C code, with f() being in a .dll library:

struct CS cs; cs.barray = new unsigned char[len]; cs.iarray = 0; int rv = f(cs);

I have code that looks like the following, and it is failing. During invocation the field s.memory is still null, causing an exception. What am I doing wrong? (I hope that during simplification of my code to get the snippet below, I didn't discard the problem...) I think the problem is not barray, but rather iarray. How do I set it null?

public class S extends Structure { public byte[] barray; public int[] iarray; public S(byte []obs) { barray = obs; iarray = null; } }

In structures where fields must be initialized, you must explicitly call allocateMemory() after initialization is complete.