Categories: MSDN / DotNet / Java / Scripts / Linux / PHP Ask - La ask - La Answer

method to return a 2-d array.

I want a C++ method to return a 2-d array. I don't want a reference/pointer because I intend to call this from Java (wrapped with JNI) and I don't know that that would work
How do I do this? This doesn't work:
int[][] MyClass::getSomeValue()
[274 byte] By [allelopath] at [2007-11-11 10:30:45]
# 1 Re: method to return a 2-d array.
How much will the calling Java process know about the array that it will be receiving from the C++ process? Can it receive it in a string or a stream? Then your C++ method could return the row-major output from the array as a string or an output stream and the Java process could read it and reconstruct the array [you could even add, at the front, the sizes of the arrays to allow some "run time" adjustment].
nspils at 2007-11-11 20:58:42 >
# 2 Re: method to return a 2-d array.
It is an array of objects of which I can probably duplicate the class in Java (it is simple, 1 integer and 3 floats).

I see your point about returning the dimensions of the array, that would smooth things. How would I return those in addition to the array itself?

But still, I don't see how to return an array, even in the simple case of returning int[][]

I am not a C++ programmer.
allelopath at 2007-11-11 20:59:43 >
# 3 Re: method to return a 2-d array.
Actually, you don't have to return the two dimensions; simply used in-out parameters that the callee will update:
void func(int& firstdim, int& seconddim);

Alternatively, pack all this info in a struct and return that struct by value. If it has only two ints, it shouldn't incur any performance penalties.
Danny at 2007-11-11 21:00:42 >
# 4 Re: method to return a 2-d array.
int ** foo() will return a 2-d array, however I almost always prefer to self index 2-d from a one-d array for a variety of reasons (easier to reshape, transpose, etc -- most of my work is linear algebra).
jonnin at 2007-11-11 21:01:37 >