JNI: equivalent of uint *vboIds in Java - java

I'm developing a java application that uses some jni calls.
I have on C code the following variable:
GLuint *vboIds;
I want to pass this variable from Java to C, but I don't know how to declare it in Java.
GLuint is equivalent an unsigned int.
So, I think this is the equivalent declaration in Java:
int[] vboIds;
What do you think?
Thanks

You don't say explicitly whether it is meant to be a pointer to a single value or an array, but I'd guess it's probably an array from the naming and what you are thinking of doing with the mapping (there should also be a parameter somewhere that specifies the length of the array; those both map to the same argument on the Java side as Java's arrays know their own lengths). You're probably right to use an int as that's generally the same size as a C int – not that that's a guarantee, not at all, but hardly any machine architectures are different from that these days – but you'll need to watch out for the fact that Java's numeric types are all signed. That's mostly not a problem provided you're a bit careful with arithmetic (other than addition, subtraction and left-shift, which work obviously) and comparisons.

Related

How can everything be an object? [closed]

Closed. This question does not meet Stack Overflow guidelines. It is not currently accepting answers.
This question does not appear to be about programming within the scope defined in the help center.
Closed 7 years ago.
Improve this question
In Java for example there is the primitive data type "int" which represents a 32 Bit value and there is "Integer" which is just a class with a single "int" property (and some methods of course). That means that a Java "Integer" class still uses primitives behind the scenes. And that's the reason Java is not a pure object oriented programming language.
Where could a value be stored if there where no primitives? For example I imagine this pseudo class:
class Integer
{
private Integer i = 12;
public Integer getInteger
{
return this.Integer;
}
}
This would be recursive.
How can a programming language be implemented without primitives?
I appreciate any help solving my confusion.
Behind the scene always will be primitives because it just a bits in memory. But some languages hide primitives that You can work only with objects. Java allows You to work both with objects and primitives.
If you mean by primitives value types, then yes you can live without them as a user and use Integer instead of int and pay for the overhead of heap allocation and GC. But this doesn't come for free and you have to pay the cost. Primitives like 32-bit/64-bit integers and IEEE-754 floating points will always be faster because there is a hardware support for them.
From a compiler writer point of view you have to use what the machine supports to make things work.
LISP is a very simple functional language. The basic LISP did not have a primitive int and one solution to integers was to have successor of successor of successor of zero for 3.
This actually had some advantages, integers being open ended, no overflow so operations really commutative, associative, and so on. Some nice optimizations possible. And of course succ(succ(succ(zero))) could be encoded in a more tuple like way (probably better not in LISP).
In a later, normal, LISP '3' would be an atom, 123 would be such an atom, with math operators.
Then there are symbol manipulating languages (SNOBOL) that could do math on numerical strings ['4', '0'] * ['3'].
So names are objects (atoms) like a char 'a' or int 42.
It might help to show you the analogous code in a language that takes the "everything is an object" design principle much more seriously than Java does. Namely, Smalltalk. Imagine what it would be like if Java had only int, not Integer, but everything you used to need to use Integer for was possible with int. That's Smalltalk.
This is an excerpt of the code defining the SmallInteger class in Squeak 5.0:
Integer immediateSubclass: #SmallInteger
instanceVariableNames: ''
classVariableNames: ''
poolDictionaries: ''
category: 'Kernel-Numbers'!
!SmallInteger commentStamp: 'eem 11/20/2014 08:41' prior: 0!
My instances are at least 31-bit numbers, stored in twos complement
form. The allowable range in 32-bits is approximately +- 10^9
(+- 1billion). In 64-bits my instances are 61-bit numbers,
stored in twos complement form. The allowable range is
approximately +- 10^18 (+- 1 quintillion). The actual
values are computed at start-up. See SmallInteger class startUp:,
minVal, maxVal.!
!SmallInteger methodsFor: 'arithmetic' stamp: 'di 2/1/1999 21:31'!
+ aNumber
"Primitive. Add the receiver to the argument and answer with the result
if it is a SmallInteger. Fail if the argument or the result is not a
SmallInteger.
Essential, No Lookup. See Object documentation whatIsAPrimitive."
<primitive: 1>
^ super + aNumber! !
!SmallInteger class methodsFor: 'instance creation' stamp: 'tk 4/20/1999 14:17'!
basicNew
self error: 'SmallIntegers can only be created by performing arithmetic'! !
Don't sweat the fine details of syntax or semantics. What you should get out of this is: SmallInteger is defined as an object class just like everything else in the language, and arithmetic operations are methods just like every other piece of code in the language. But it's a little odd. It has no instance variables, you can only create instances by performing arithmetic, and most of the methods look like they're being defined circularly.
"Under the hood", the implementation maps arithmetic to the appropriate machine instructions (the <primitive: 1> thing is a hint to the implementation about that) and stores SmallIntegers as nothing more than the integer itself. The restricted range, relative to the hardware, is because a couple of bits are reserved to mark memory words as integers, rather than pointers to objects ("tagged pointers").
Without being able to eventually access real data, (eg. primitives or actual bits) (directly or indirectly) on a machine, it is no longer a programming language, it is an Interface Description Language.
(I'll rephrase the question to what I believe you're asking. If you think I've got it wrong, feel free to comment.)
How can a type system that's based on composition and inheritance define any useful type, if there are no intrinsic types to start from? Unless the language implementation knows about at least one intrinsic type to start from, any defined types would be doomed to be either recursive or empty. Is this inevitable?
Yes, in every C-family language that I know of, this is pretty much inevitable.
If every type is composed of other types then, at the very least, you need to have an intrinsic type to build upon - for example, an intrinsic type that represents a bit, in order to construct the byte type out of it through composition, then the word type, then various integer types, and so on. Then you'd need to define the operations that can be performed on these types, by manipulating the bits that make up their internal representation.
And even though all you need is one intrinsic type to build upon, it would likely be terribly inefficient - you don't want to waste space or CPU cycles and you do want to take advantage of the various storage locations and instructions that your target architecture offers, including FP registers and other stuff.
Thus, a good compromise between performance and "purity" is to offer in the language some intrinsic types that are likely to be recognizable by modern CPUs (like int32, int64, float, double, etc) and build the rest of the type system upon them. In Java, they decided to call these intrinsic types primitives and make them separate from classes.
Eventually everything comes back to bits in memory and instructions to the computer. The difference between assembler, compiled, procedural, object oriented, and all the other things is how much abstraction there is between you and the bits and how much benefit (or cost) you get from that abstraction.

How to add pointers in Java programming language?

I am trying to convert the C++ programs into Java programs but I am not able to get the syntax of pointers in java programming language. What should I do?
Your question is very vague because you haven't specified what you need the pointers for. If you need pointer arithmetic, the closest thing in Java is the Unsafe API, which is proprietary and not part of the official JDK API.
If you need to just pass pointers around and dereference them, no syntax for that is needed in Java—actually you must remove the syntax from C++ code to get the equivalent in Java:
ptr->method() converts to ptr.method()
*ptr becomes just ptr
&obj becomes just obj.
This is because Java exclusively uses pointers to refer to objects, so the syntax simply assumes them.
Firstly, there's no pointers (actually, everything, except primitives, is a pointer, but you want to change passed variable, ain't you?) in Java, so you should think of how you can implement the same functionality without pointers.
If you can't succeed in this, you can make your methods accept something, which holds reference for another variable, for example, AtomicReference<T> (AtomicInteger/AtomicLong for, correspondingly, int and long).
It would be something like:
void changeMyString(AtomicReference<String> ref) {
ref.set("Hello, World!");
}

How is array passed to a function?

Consider the following:
String[] array = {1,2,3,4};
myFunction(array);
public void myFunction(String[] array){
//some task here
}
I had to answer this question today.
How are arrays passed to a function? Means what is the underlying technique?
When I failed to answer, I was told the following.
The address of first element is passed and other consecutive elements are obtained from the first element's address by adding some x bytes.
Does this happen in every programming language or in just c and c++?
Thank you!
No, in Java for example arrays are objects. They are passed like any other object is passed to a method: the method would take a reference to the array object as a whole, and not a reference to the first element.
Taken from this page:
All class and array types inherit (§8.4.8) the methods of class Object
Java has no concept of "pointers", in the same sense as C or C++ (addresses in memory), i.e. an object reference does not really point to the memory location where the object is stored.
In theory, every language is different. However:
In C, a function cannot take an array as an argument. When
you declare an array parameter, the type is automatically
converted into a pointer, so there is no different between
void f( int a[5] ) and void f( int* ). (This is often
summarized by saying that arrays are not first class objects.)
For reasons of C compatibility, C++ follows the same rules, but
in C++, you wouldn't normally pass an array as a parameter
anyway, and if you did, you would pass it by reference, where
this conversion to pointer doesn't occur. (I.e.
void f( int (&a)[5] ) is not the same as void f( int* &a ).)
In Java, and a number of other recent languages, everything
(or almost), including arrays are objects, and parameters,
variables, etc. are pointers to those objects. So in Java, you
pass a pointer to the array, but the full array object, with
all of the information about its size, etc. Sort of like
passing an std::vector<int>* in C++.
In a lot of languages (mostly older?), like Pascal and
languages of the Modula family, and array is an object type just
like any other. If you don't take any particular actions, an
array will be passed by value, with a complete copy of the
array.
And in the earliest languages, like Fortran or Algol, each
language often had its own very particular ways of passing
arrays, although in general, they followed the same rules as other
types. (Some early languages like Cobol or Basic, didn't even
support passing arguments to functions, at least in their
earliest variants.)
Amongst the languages you're likely to see today, I think that
the Java model predominates. C remains an outlier, and C++
gives you the choice: you can pass an std::vector by value or
by reference (but reference is recommended for performance
reasons).

java - Convert a byte array to a class?

In C/C++, you can do the following:
struct DataStructure
{
char member1;
char member2;
};
DataStructure ds;
char bytes[] = {0xFF, 0xFE};
memcpy(&ds, bytes, sizeof(ds));
and you would essentially get the following:
ds.member1 = 0xFF;
ds.member2 = 0xFE;
What is the Java equivalent?
What is the Java equivalent?
There is no Java equivalent.
Java does not allow you to create or modify objects by accessing them at that level. You should be using new or setter methods, depending on what you are trying to achieve.
(There are a couple of ways to do this kind of thing, but they are unsafe, non-portable and "not Java" ... and they are not warranted in this situation.)
The memcpy you wrote depends on the internal implementation of the struct and would not necessarily work. In java, you need to define a constructor that accepts a byte array and set the fields. No shortcuts like this, as the memory structure of the class is not defined.
In Java you cannot work with the memory directly (no memcpy) it is the advantage (disadvantage?) of Java. There are some java library methods to copy arrays: System.arraycopy().
In general, to copy some object you need to ship it with clone method.
You might be able to do that in C. But you'd be wandering into aliasing problems and a hunka hunka burning undefined behavior.
And because struct padding is up to a compiler, what you might get with your memcpy is just ds.member1 = 0xFF, ds.member2 = whatever junk happened to be on the stack at the time, because member1 was padded to occupy 4 bytes rather than just 1. Or maybe you get junk for both, because you set the top 2 bytes of a 4-byte and they're in the bottom 2 bytes.
What you're wandering into is compiler/runtime-specific memory layouts. The same is true in Java. Java itself won't let you do something so horrendously un-Java, but if you write your own JVM or debug an existing JVM written in C or C++, you could do something like that. And who knows what would happen; I'm not Java god enough to know exactly how much the JVM spec pins down JVM implementation, but my guess is, not to the degree necessary to enable interoperability of the in-memory, runtime representations of objects.
So you get undefined behavior in every language flavor. Tastes just as good in each language, too - like mystery meat.

Passing dynamic list of primitives to a Java method

I need to pass a dynamic list of primitives to a Java method. That could be (int, int, float) or (double, char) or whatever. I know that's not possible, so I was thinking of valid solutions to this problem.
Since I am developing a game on Android, where I want to avoid garbage collection as much as possible, I do not want to use any objects (e.g. because of auto boxing), but solely primitive data types. Thus a collection or array of primitive class objects (e.g. Integer) is not an option in my case.
So I was thinking whether I could pass a class object to my method, which would contain all the primitive vales I need. However, thats neither a solution to my problem, because as said the list of primitives is variable. So if I would go that way in my method I then don't know how to access this dynmic list of primitives (at least not without any conversion to objects, which is what I want to avoid).
Now I feel a bit lost here. I do not know of any other possible way in Java how to solve my problem. I hope that's simply a lack of knowledge on my side. Does anyone of you know a solution without a conversion to and from objects?
It would perhaps be useful to provide some more context and explain on exactly what you want to use this technique for, since this will probably be necessary to decide on the best approach.
Conceptually, you are trying to do something that is always difficult in any language that passes parameters on a managed stack. What do you expect the poor compiler to do? Either it lets you push an arbitrary number of arguments on the stack and access them with some stack pointer arithmetic (fine in C which lets you play with pointers as much as you like, not so fine in a managed language like Java) or it will need to pass a reference to storage elsewhere (which implies allocation or some form of buffer).
Luckily, there are several ways to do efficient primitive parameter passing in Java. Here is my list of the most promising approaches, roughly the order you should consider them:
Overloading - have multiple methods with different primitive arguments to handle all the possible combinations. Likely to be the the best / simplest / most lightweight option if there are a relatively small number of arguments. Also great performance since the compiler will statically work out which overloaded method to call.
Primitive arrays - Good way of passing an arbitrary number of primitive arguments. Note that you will probably need to keep a primitive array around as a buffer (otherwise you will have to allocate it when needed, which defeats your objective of avoiding allocations!). If you use partially-filled primitive arrays you will also need to pass offset and/or count arguments into the array.
Pass objects with primitive fields - works well if the set of primitive fields is relatively well known in advance. Note that you will also have to keep an instance of the class around to act as a buffer (otherwise you will have to allocate it when needed, which defeats your objective of avoiding allocations!).
Use a specialised primitive collection library - e.g. the Trove library. Great performance and saves you having to write a lot of code as these are generally well designed and maintained libraries. Pretty good option if these collections of primitives are going to be long lived, i.e. you're not creating the collection purely for the purpose of passing some parameters.
NIO Buffers - roughly equivalent to using arrays or primitive collections in terms of performance. They have a bit of overhead, but could be a better option if you need NIO buffers for another reason (e.g. if the primitives are being passed around in networking code or 3D library code that uses the same buffer types, or if the data needs to be passed to/from native code). They also handle offsets and counts for you which can helpful.
Code generation - write code that generates the appropriate bytceode for the specialised primitive methods (either ahead of time or dynamically). This is not for the faint-hearted, but is one way to get absolutely optimal performance. You'll probably want to use a library like ASM, or alternatively pick a JVM language that can easily do the code generation for you (Clojure springs to mind).
There simply isn't. The only way to have a variable number of parameters in a method is to use the ... operator, which does not support primitives. All generics also only support primitives.
The only thing I can possibly think of would be a class like this:
class ReallyBadPrimitives {
char[] chars;
int[] ints;
float[] floats;
}
And resize the arrays as you add to them. But that's REALLY, REALLY bad as you lose basically ALL referential integrity in your system.
I wouldn't worry about garbage collection - I would solve your problems using objects and autoboxing if you have to (or better yet, avoiding this "unknown set of input parameters" and get a solid protocol down). Once you have a working prototype, see if you run into performance problems, and then make necessary adjustments. You might find the JVM can handle those objects better than you originally thought.
Try to use the ... operator:
static int sum (int ... numbers)
{
int total = 0;
for (int i = 0; i < numbers.length; i++)
total += numbers [i];
return total;
}
You can use BitSet similar to C++ Bit field.
http://docs.oracle.com/javase/1.3/docs/api/java/util/BitSet.html
You could also cast all your primitives to double then just pass in an array of double. The only trick there is that you can't use the boolean type.
Fwiw, something like sum(int... numbers) would not autobox the ints. It would create a single int[] to hold them, so there would be an object allocation; but it wouldn't be per int.
public class VarArgs {
public static void main(String[] args) {
System.out.println(variableInts(1, 2));
System.out.println(variableIntegers(1, 2, 3));
}
private static String variableInts(int... args) {
// args is an int[], and ints can't have getClass(), so this doesn't compile
// args[0].getClass();
return args.getClass().toString() + " ";
}
private static String variableIntegers(Integer... args) {
// args is an Integer[], and Integers can have getClass()
args[0].getClass();
return args.getClass().toString();
}
}
output:
class [I
class [Ljava.lang.Integer;

Categories

Resources