Populate and Pass an Array of Structures to Java - java

I have spent a large portion of the morning trying to populate and pass an array of populated structs to C++ from Java using JNA. I have significant portions of JNA based code running and I feel like this should be simple, but I can not figure out or find an example that does not use #deprecated functions. My suspicion is that this is trivial and I'm going to feel dumb when someone shows me, but I would really appreciate some help.
A little background on what I have tried:
I somehow doubt it matters, but after learning how to write the interface files by hand (and getting them to work), I switched over to JNAerator. JNAerator translates
MyStruct* mine
to
MyStruct mine
in Java. This confuses me a bit because in Java this could only be used to point to a single object. At one point I looked at using
MyStruct** mine
which translates to
PointerByReference mine
But this seems like overkill because I don't need to modify the structs, or ever access them again for that matter. I have tried everything I can think of from this point on but I have never managed to successfully send more than the first struct.

After re-reading your question (pass structures from Java to C++), here's what you can do:
// Assuming a native signature like this:
// call_native_function(MyStruct** struct_list, int count)
MyStruct.ByReference[] list = new MyStruct.ByReference[SIZE];
for (int i=0;i < list.length;i++) {
list[i] = new MyStruct.ByReference();
// Initialize the struct as needed
}
// Call whatever native method...
nativeLibrary.call_native_function(list, list.length);
See also the JNA FAQ.

Related

Using a C++ Struct in Android app (Java and XML)?

I'm a decent C++ programmer, good enough to do what I want. But I'm working on my first Android App (obviously not C++ related), and I'm having an issue where I'd like to translate what I know from C++ over to the XML/Java used in Android Studio.
Basically I have (in C++) an array of structures. And maybe I didn't do the perfect search, but I sure as heck tried to look around for the answer, but I didn't come up with anything.
How would I go about placing an array of structures inside the XML file and utilizing it in Java?
As a bit of a buffer, let me say that I'm not really looking for code, just verification that this is possible, and a method on how to go about it. I don't mind researching to learn what I want, but I haven't come up with anything. Like I said, I probably haven't googled it properly because I'm unsure of exactly how to ask it.
EDIT: So it appears that XML doesn't have a structure (or anything similar? not sure). But I can utilize a Java class with public variables. Now my question is more or less: What would be the best way to go about inserting all the information into the array/class/variables?
In C++ terms, I could neatly place all the info into a text file and then read from it, using a FOR loop to place all the info in the structures. Or, if I don't want to use an outside source/file, I could hardcode the information into each variable. Tedious, but it'd work. I'm not sure, in Android terms, if I could use the same method and pack in a text file with the app, and read from the file using a FOR loop to insert the information into the array/class/variables
class answerStruct
{
public String a;
public boolean status;
};
class questionStruct
{
public String q;
answerStruct[] answer = new answerStruct[4];
};
I'm not placing this here to brag at my super high tech program, but to give a visual, and frankly that's less I have to write out. This is the method I plan on going with. But, being Java, I'm open to possibly better options. My question still stands as far as inputting information into the variables. Hard code? or does Android/Java allow me to place a text file with my app, and read from it into the variables?
XML is just a markup language for tree-structured data, and imposes no restrictions on how you name or structure your tree nodes.
What I think that you're looking for is an XML Object Serialiser: a way to serialise your in-memory structure into XML for a more permanent storage, and then at a later run, deserialise it back into memory. There are many XML Serialisers for Java, each with an own proprietary XML format.
I've used Simple XML in the past, and found it easy and flexible.

Java library for creating 3d-objects for 3d printing

I am looking for a java library to create 3d-geometries and then convert that to .stl files so I can 3d print my object using a 3d printer.
I can imagine using a 3d-graphics object where one can draw the same like on a graphics2d object:
Buffered3DObject obj = new Buffered3DObject(200,200,200, Unit.MM);
Graphics3D g3 = obj.getGraphics();
Stroke3d stroke = new Stroke(3);
g3.setStroke(stroke);
g3.drawpipe(x1,y1,z1,x2,y2,z2);
obj.exportToSTL("filename.stl");
Ok, I am just making up code :). But something like this.
Anybody know how I could pull something like this off? Any opensource libs that does stuff like this?
Would be nice to be able to generate a customized object through user input from a website.
Rob.
Edit:
Even though the question is closed (and nobody cared to answer my question on why) I found my answer (I post it so others with the same question can find it):
There is a java library on its way as a wrapper around OpenScad. The java wrapper is called JavaScad. Can be found here JavaScad
There is a java library which works as a wrapper around OpenScad. The java wrapper is called JavaScad. Can be found here JavaScad. It works fine and I actually contributed to the library already.
JCSG - Java implementation of BSP based CSG (Constructive Solid Geometry)
jsolid - wrapper around JCSG providing fluent API
Another option is: abfab3d.com This is opensourced code from Shapeways. Its is more complex and uses voxels as a base, but can convert to mesh aswell.
The code is at github: abfab3d # github
I have not tried it, but will as the openscad route is slow and difficult to integrate in a webserver, so I will try it once I have time.

Automatically generate Java code based on existing fields in a class

Scenario
I'm working with a Java model built from scratch in Eclipse. What's important in this model is that we save our output to MATLAB (.mat) files. I constantly add new features, which require new fields that in turn will have to be exported to the .mat file at every iteration. Upon restarting a crashed simulation, I might have to import the .mat file. To export or import my .mat file I use JMatIO.
For example, if I would add a new field rho_m (a simple double) to my class CModel, I have to add to my Save() method:
mlModel.setField("rho_m", new MLDouble(null, new double[] {rho_m}, 1));
And to my Load() method:
rho_m = ((MLDouble)mlModel.getField("rho_m")).getReal(0);
Note that even though rho_m is a double, it needs to be treated as a double[] in JMatIO. This probably has something to do with MATLAB being orientated towards matrices and matrix operations.
Problem
Instead of doing this manually (prone to errors, annoying to maintain) I would like to automate this procedure. Ideally, I would like my IDE to detect all the fields in CModel and write the code based on the field's name and type. Is there any way to do this in Java/Eclipse?
Ideas so far
I have no formal training in low-level programming languages (yes, Java is low-level to me) and am still relatively new to Java. I do have some experience with MATLAB. In MATLAB I think I could use eval() and fieldnames() in a for loop to do what I mentioned. My last resort is to copy-paste the Java code to MATLAB and from there generate the code using a huge, ugly script. Every time I want to make changes to the model I'd rerun the MATLAB script.
Besides that idea I've found terms like UML, but do not have the background knowledge to figure out if this is what I'm looking for or not.
Any help, even if it's just a small push in the right direction, is greatly appreciated. Let me know if I need to further clarify anything.
Looking at your scenario, you are doing model-driven code generation, that is, you have a model and want to get some code generated according to your current model. Therefore, you need a model-driven code generator.
I lead the ABSE/AtomWeaver project, so I'll outline what you can do to get what you want using AtomWeaver (There are however other solutions like MetaEdit+, XText or Eclipse's own GMT/EMF sub-system).
AtomWeaver is an IDE where you can build a model and generate code from that model. You can change your model as many times you want and hit the "Generate" button to get an updated version of your code. ABSE is the name of the modeling method.
We don't need to go into details, but essentially ABSE follows a "building-block" approach. You create a Template that represents a feature or concept of your model. Then, you can associate a mini-code generator just to that concept. You can then "instantiate" and combine those building blocks to quickly build your models. Variables increase the flexibility of your models.
You can also change your models, or add new features ("blocks") and generate again. The generators are built using the Lua programming language, a very simple language with C-Like syntax.
The best way to understand the ABSE development method and the AtomWeaver IDE is to download the IDE and see the samples or try the tutorials. And yes, you can use AtomWeaver for free.

Java implementation for LDPC codes

Is there any open source Java implementation for LDPC (Low Density Parity Check) codes, I found only MATLAB codes.
My scenario is I will take text file and divide into block and I will delete some data in text file, and by using LDPC codes I need to recover data from text files.
Thanks.
I haven't tried this but the code here should get you started
http://www.cs.utoronto.ca/~radford/ftp/LDPC-2006-02-08/install.html
http://www.cs.utoronto.ca/~radford/ftp/LDPC-2006-02-08/examples.html
It's in C though. Might be easy to port. Or not.
I'd suggest looking into ways of calling matlab functions in java. I know there are a couple. Also why LDPC? While its one of the best FEC, it involves lots of matrix manipulation if I recall correctly. This is stuff much better suited for mat[rix]lab. The right tool for the right job...
There are also these two pure Java implementations:
https://github.com/a4a881d4/ldpc-java
https://github.com/pierroweb/LDPC-correcting-codes
I haven't tested them and would appreciate feedback from anyone else that has.
There's also a Java wrapper around a C++ library: http://cpham.perso.univ-pau.fr/MULTICAST/Java_wrapper_for_LDPC.html
Not the most promising results, but something to start from, at the very least.

Using a utility to generate Java code to make my project more concise. Good idea?

The project I'm working on requires me to write lots of repetitive code. For example, if I want to load a image file called "logo.png" in my code, I would write something like this:
Bitmap logoImage;
...
// Init
logoImage = load("logo.png")
...
// Usage
logoImage.draw(0, 0);
..
// Cleanup
logoImage.release();
Having to write this code to use every new image is a pain, including having to specify that logoImage should load the file "logo.png".
As I'm working on a Java Android game and images are used a lot in inner loops, I really want to avoid slow things like making virtual function calls and e.g. accessing arrays/maps/object fields when I can avoid it. Copying an idea from the Android API (the generated R class), I thought I could run a utility before compiling to generate some of this repetitive code for me. For example, the actual code in the project file would be reduced to just this:
logoImage.draw(0, 0);
Using some command-line tools (e.g. grep, sed), I can look for every instance of "Image.draw(..." and then generate the other required code automatically i.e. code to load/release the file .png and declare "Bitmap logoImage" somewhere. This code could either be added to a new class or I could add placeholders in my code that told the code generator where to insert the generated code.
To display a new image, all I would need to do is just copy the image file to the right directory and add one line of code. Nice and simple. This avoid approaches like creating an array of images, defining labelled int constants to references the array and having to specify which filename to load.
Is this a really bad idea? It seems a bit of a hack but I can see no easier way of doing this and it does seem to drastically clean up my code. Are there any standard tools for doing this simple kind of code generation (i.e. the tool doesn't need to understand the meaning of the code)? Does anyone else do things like this to make up for language features?
It would be a bad idea to use code generation for something like this. (IMO, code generation should be reserved for situations where you need to generate vast amounts of code, and this doesn't sound like that situation.)
If the boilerplate code in your current solution concerns you, a better solution (than code generation) is to implement an image registry abstraction; e.g.
public class ImageRegistry {
private Map<String, Image> map = new HashMap<String, Image>();
public synchronized Image getImage(String filename) {
Image image = map.get(filename);
if (image == null) {
image = load(filename);
map.put(filename, image);
}
return image;
}
public synchronized void shutdown() {
for (Image image : map.valueSet()) {
image.release();
}
map.clear(); // probably redundant ...
}
}
Replace logoImage.draw(0, 0) and the like with:
registry.getImage("logo.png").draw(0, 0);
remove all of the load calls, and replace all of the release calls with a single call to registry.shutdown().
EDIT in response to the OP's comments below:
... but I mention that I'm writing a game for a phone. A HashMap lookup every time I'm drawing a sprite will kill performance.
Ah ... I remember you from another thread.
You are (yet again) making assumptions about performance without any basis in actual performance measurements. Specifically, you are assuming that HashMap lookup is going to be too expensive. My gut feeling is that the time taken to do the lookup will be a small percentage ( < 10% ) of the time taken to draw the image. At that point, it is approaching the level at which it is unnoticable to users.
If your measurements (or gut feeling) tells you that a hashmap lookup is too expensive, it is a trivial modification to write this:
Image image = registry.getImage("logo.png");
while (...) {
...
image.draw(0, 0);
}
For example, Google even go as far as to recommend you don't use iterators in inner loops because these cause the GC to fire when the Iterator objects are deallocated.
That is irrelevant and inaccurate.
A HashMap lookup using a String key does not generate garbage. Not ever.
Using an iterator in an inner loop does not "cause the GC to fire when the Iterator objects are deallocated". In Java, you don't deallocate objects. That is C/C++ thinking.
Instantiating an iterator in an inner loop does new an object, but the GC will only fire if the new operation hits the memory threshold. This happens only occasionally.
Also, writing "file_that_does_not_exist.png" will not be picked up as a compile time error with your example.
Neither your original solution, or the code generation approach can give you a compile time error for a missing file either.
Avoid code-generation. It often makes code hard to maintain.
In your case why don't you just make:
public class ImageUtils {
public static void drawAndRelease(String name) {
logoImage = load(name)
logoImage.draw(0, 0);
logoImage.release();
}
}
and then just call:
ImageUtils.drawAndRelease("logo.png");
If there is more code between these methods - well, then they are atomic methods and you won't know where to put them in case you use code-generation.
I second Bozho's answer about avoiding code generation, but if you have to write repeatable snippets of code, any good IDE usually has some built in support for specifying your own snippets with variables and everything. IntelliJ IDEA has this feature, it's called Live Templates. I would guess both Eclipse and NetBeans has similar functionality.
You transfer complexity to code generation, and it (generation) is not trivial and may be buggy.
Code is harder to read and maintain. Some clear rules to design and coding are more helpful here.
Several ways:
Eclipse code2code, you cod in template using template language such as FreeMarker, groovy, etc
eclipse sqLite plugin for Android autogenerates sqlite code
MotoDevStudio4android has code snippets which yo could use

Categories

Resources