Fatal error with JNA structure - jna

I have a problem with a very simple example in jna. I would like to read and write in a structure in C with java. I compiled a very simple example in c:
typedef struct {
int x;
} MyStruct;
I created the corresponding class in java with JNA:
import java.util.List;
import com.sun.jna.Pointer;
import com.sun.jna.Structure;
public class MyStruct extends Structure {
public int x;
public MyStruct(Pointer p) {
super(p);
}
#Override
protected List<String> getFieldOrder() {
return List.of("x");
}
}
And I created a program to test the structure:
public class JnaJava {
public static void main(String[] args) {
NativeLibrary lib = NativeLibrary.getInstance(new File("libJnaC.so").getAbsolutePath());
MyStruct struct = new MyStruct(lib.getGlobalVariableAddress("myStruct"));
for (int i = 0; i < 2000000000; i++) {
struct.writeField("x", i);
System.out.println("val: " + struct.readField("x") + " it: " + i);
}
}
}
But I have an error around the 400.000 iterations:
...
val: 448536 it: 448536
# A fatal error has been detected by the Java Runtime Environment:
# SIGSEGV (0xb) at pc=0x00007fb3d89e537b, pid=14464, tid=14466
# JRE version: Java(TM) SE Runtime Environment (10.0+46) (build 10+46)
# Java VM: Java HotSpot(TM) 64-Bit Server VM (10+46, mixed mode, tiered, compressed oops, g1 gc, linux-amd64)
# Problematic frame:
# C [jna8855397332554224295.tmp+0x837b] Java_com_sun_jna_Native_setInt+0xab
# No core dump will be written. Core dumps have been disabled. To enable core dumping, try "ulimit -c unlimited" before starting Java again
# An error report file with more information is saved as:
# /home/X/workspace/JnaJava/hs_err_pid14464.log
# If you would like to submit a bug report, please visit:
# http://bugreport.java.com/bugreport/crash.jsp
# The crash happened outside the Java Virtual Machine in native code.
# See problematic frame for where to report the bug.
Can someone tell me where is my mistake? It sounds like a strange memory bug but I don't know why?
Thanks in advance
Marc

It was just a stupid GC problem. Put the variable in in a strong reference solved the problem.
https://groups.google.com/forum/#!topic/jna-users/4g3fLVi8Gxw

Related

POJO compilation fails (Algo: GBM, H2o-Version 3.8.1.3, Javac: 1.8.0_45, Mac OSX 10.11.3 / Fedora 23)

I try to locally compile a POJO of a GBM prediction model generated with H2o 3.8.1.3; I follow the instructions in the POJO class:
create a folder
Download the h2o-genmodel.jar into the folder with:
curl http://myh2oinstancesurl:myh2oinstancesport/3/h2o-genmodel.jar > h2o-genmodel.jar
Download the successfully trained GBM model named 154 into the folder with:
curl http://myh2oinstancesurl:myh2oinstancesport/3/Models/154/java > 154.java
Compile the sources in the folder with javac 1.8.0_45 under Max OSX 10.11.3 or Fedora 23:
javac -cp h2o-genmodel.jar 154.java
Result are a bunch of compilation errors:
154.java:24: error: <identifier> expected
public class 154 extends GenModel {
^
154.java:24: error: illegal start of type
public class 154 extends GenModel {
^
154.java:24: error: ';' expected
public class 154 extends GenModel {
^
154.java:25: error: illegal start of expression
public hex.ModelCategory getModelCategory() { return hex.ModelCategory.Binomial; }
^
154.java:25: error: ';' expected
public hex.ModelCategory getModelCategory() { return hex.ModelCategory.Binomial; }
^
154.java:27: error: illegal start of expression
public boolean isSupervised() { return true; }
^
154.java:27: error: ';' expected
public boolean isSupervised() { return true; }
^
154.java:28: error: illegal start of expression
public int nfeatures() { return 14; }
^
154.java:28: error: ';' expected
public int nfeatures() { return 14; }
^
154.java:29: error: illegal start of expression
public int nclasses() { return 2; }
^
...
100 errors
Is there an issue with my procedure? Or is this a bug with my setup? Is there anybody who currently can compile GBM POJOs? Thanks for your responses!
Solved: The problem was that the POJO class name obviously has to be a valid java class name; a purely numeric name is not allowed. Changing the model name resolves the issue.
[ This is not a direct answer to the question, but hopefully a helpful pointer to anyone that finds this question... ]
Since this question was asked, H2O has also added the ability to export a MOJO and use it for making predictions.
An H2O POJO is a code representation of a model, and an H2O MOJO is a data representation of a model.
A MOJO can be used in the same way as a POJO, and MOJOs do not need to be compiled (they are interpreted instead). This is especially useful for very large tree models, where trying to compile them has various technical challenges around gigabytes of code size. So in many cases, the best way to address a compilation issue is to not compile at all.
The online documentation for both H2O POJOs and MOJOs can be found here:
http://docs.h2o.ai/h2o/latest-stable/h2o-genmodel/javadoc/index.html
I hope people find this (delayed) answer helpful.

Exception in thread "main" java.lang.Error: Unresolved compilation problems: JNI4net

I am working with JNI4net and although the libraries and installed in the build path and eclipse recognizes them, it still gives me run time error. Why could that be in your opinion? Here is the code.
import net.sf.jni4net.*;
import java.io.IOException;
import java.lang.String;
import system.*;
import system.Object;
import system.io.TextWriter;
import system.collections.IDictionary;
import system.collections.IEnumerator;
/**
* #author Pavel Savara (original)
*/
public class Program {
public static void main(String[] args) throws IOException {
// create bridge, with default setup
// it will lookup jni4net.n.dll next to jni4net.j.jar
//Bridge.setVerbose(true);
Bridge.setVerbose(true);
Bridge.init();
// here you go!
Console.WriteLine("Hello .NET world!\n");
// OK, simple hello is boring, let's play with System.Environment
// they are Hashtable realy
final IDictionary variables = system.Environment.GetEnvironmentVariables();
// let's enumerate all keys
final IEnumerator keys = variables.getKeys().GetEnumerator();
while (keys.MoveNext()) {
// there hash table is not generic and returns system.Object
// but we know is should be system.String, so we could cast
final system.String key = (system.String) keys.getCurrent();
Console.Write(key);
// this is automatic conversion of JVM string to system.String
Console.Write(" : ");
// we use the hashtable
Object value = variables.getItem(key);
// and this is JVM toString() redirected to CLR ToString() method
String valueToString = value.toString();
Console.WriteLine(valueToString);
}
// Console output is really TextWriter on stream
final TextWriter writer = Console.getOut();
writer.Flush();
}
}
AND here is the message I get!
Exception in thread "main" java.lang.Error: Unresolved compilation problems:
Bridge cannot be resolved
Bridge cannot be resolved
Console cannot be resolved
IDictionary cannot be resolved to a type
system cannot be resolved
IEnumerator cannot be resolved to a type
system cannot be resolved to a type
system cannot be resolved to a type
Console cannot be resolved
Console cannot be resolved
Console cannot be resolved
TextWriter cannot be resolved to a type
Console cannot be resolved
at Program.main(Program.java:37)
To make your life easier, I am going to share my findings here. Read Martin Serrano's answer to my question. It will help you understand what needs to be done. Then go to jni4net's website and download their example zip folder. Extract that. There is an example there called myCSharpDemoCalc. Replace your dll with myCSharpDemoCalc.dll (inside work folder) and then run generateProxies.cmd (be sure to edit this file to your dll name) and run.cmd. Then go to the work folder and run build.cmd (edit name) to create your JAR file. It might not spit out the j4n.dll you probably need to twik the path yourself. Use this JAR file. This was the easiest way to create a JAR file from a third party dll for me.

Dart library visibility

My Dart app has the following structure:
myapp/
pubspec.yaml
pubspec.lock
asset/
...
web/
logging/
Logger.dart
LogLevel.dart
...other packages
Where the 2 shown Dart files are:
LogLevel.dart:
library logging;
class LogLevel {
static const TRACE = const LogLevel._(0);
static const INFO = const LogLevel._(1);
static const ERROR = const LogLevel._(2);
static get values => [TRACE, INFO, ERROR];
final int value;
const LogLevel._(this.value);
}
Logger.dart:
library logging; // <== compiler error!?!
import "package:logging/LogLevel.dart";
class Logger {
// ...
}
I figured since I put the two classes into a logging library/package together, that they would be visible to one another. But that's not the case! Instead on the import statement I get the following compiler error:
Target of URI does not exist: 'package:logging/LogLevel.dart'
What's going on here? How should I be packaging/library-ing my types differently so that they'll be visible to one another?
You can import them through their relative path without referring to the package:
import 'LogLevel.dart';
If you do want to import them as packages, they need to be under the lib folder.

Vala: number of cpus

I am trying to get my machine's number of cpus in vala.
According to http://valadoc.org/#!wiki=glib-2.0/index
public uint get_num_processors ()
should return this to me.
But when I try to compile the following code:
public class Main {
static int main(string[] args) {
uint num_cpus = GLib.get_num_processors();
return 0;
}
}
with:
valac --target-glib 2.38 --pkg gtk+-3.0 --pkg gee-1.0 $(SRC)
I see the following error:
Application.vala:28.4-28.26: error: The name 'get_num_processors' does
not exist in the context of 'GLib'
I've tested some other methods from GLib. They all work flawless except this one.
Has anyone an idea what I'm doing wrong?
The function was only added to the VAPI recently, I believe you'll need version 0.22.0 of Vala (or one of the unstable 0.21.x releases).
To get around this you can create a local binding in your code:
[CCode (cname = "g_get_num_processors")]
private extern static uint get_num_processors ();
This was introduced in GLib 2.36 (see GLib Threads). Do you have that version installed?

Using new Groovy Grape capability results in "unable to resolve class" error

I've tried to use the new Groovy Grape capability in Groovy 1.6-beta-2 but I get an error message;
unable to resolve class com.jidesoft.swing.JideSplitButton
from the Groovy Console (/opt/groovy/groovy-1.6-beta-2/bin/groovyConsole) when running the stock example;
import com.jidesoft.swing.JideSplitButton
#Grab(group='com.jidesoft', module='jide-oss', version='[2.2.1,)')
public class TestClassAnnotation {
public static String testMethod () {
return JideSplitButton.class.name
}
}
I even tried running the grape command line tool to ensure the library is imported. Like this;
$ /opt/groovy/groovy-1.6-beta-2/bin/grape install com.jidesoft jide-oss
which does install the library just fine. How do I get the code to run/compile correctly from the groovyConsole?
There is still some kinks in working out the startup/kill switch routine. For Beta-2 do this in it's own script first:
groovy.grape.Grape.initGrape()
Another issue you will run into deals with the joys of using an unbounded upper range. Jide-oss from 2.3.0 onward has been compiling their code to Java 6 bytecodes, so you will need to either run the console in Java 6 (which is what you would want to do for Swing anyway) or set an upper limit on the ranges, like so
import com.jidesoft.swing.JideSplitButton
#Grab(group='com.jidesoft', module='jide-oss', version='[2.2.1,2.3.0)')
public class TestClassAnnotation {
public static String testMethod () {
return JideSplitButton.class.name
}
}
new TestClassAnnotation().testMethod()
I finally got it working for Groovy Shell (1.6.5, JVM: 1.6.0_13). This should be documented better.
First at the command line...
grape install org.codehaus.groovy.modules.http-builder http-builder 0.5.0-RC2
Then in groovysh...
groovy:000> import groovy.grape.Grape
groovy:000> Grape.grab(group:'org.codehaus.groovy.modules.http-builder', module:'http-builder', version:'0.5.0-RC2')
groovy:000> def http= new groovyx.net.http.HTTPBuilder('http://rovio')
===> groovyx.net.http.HTTPBuilder#91520
The #grab is better used in a file than the shell.
Ok. Seems like this a short working demo (running from the groovyConsole)
groovy.grape.Grape.initGrape()
#Grab(group='com.jidesoft', module='jide-oss', version='[2.2.1,2.3.0)')
public class UsedToExposeAnnotationToComplier {}
com.jidesoft.swing.JideSplitButton.class.name
When run it produces
Result: "com.jidesoft.swing.JideSplitButton"
Very cool!!
The import statement must appear after the grabs.
Ps. At least one import statement must exists after the grabs
#Grab(group='com.jidesoft', module='jide-oss', version='[2.2.1,)')
import com.jidesoft.swing.JideSplitButton
public class TestClassAnnotation {
public static String testMethod () {
return JideSplitButton.class.name
}
}
Different example using latest RC-2 (note: Grab annotates createEmptyInts):
// create and use a primitive array
import org.apache.commons.collections.primitives.ArrayIntList
#Grab(group='commons-primitives', module='commons-primitives', version='1.0')
def createEmptyInts() { new ArrayIntList() }
def ints = createEmptyInts()
ints.add(0, 42)
assert ints.size() == 1
assert ints.get(0) == 42
Another example (note: Grab annotates getHtml):
// find the PDF links in the Java 1.5.0 documentation
#Grab(group='org.ccil.cowan.tagsoup', module='tagsoup', version='0.9.7')
def getHtml() {
def parser = new XmlParser(new org.ccil.cowan.tagsoup.Parser())
parser.parse("http://java.sun.com/j2se/1.5.0/download-pdf.html")
}
html.body.'**'.a.#href.grep(~/.*\.pdf/).each{ println it }
Another example (note: Grab annotates getFruit):
// Google Collections example
import com.google.common.collect.HashBiMap
#Grab(group='com.google.code.google-collections', module='google-collect', version='snapshot-20080530')
def getFruit() { [grape:'purple', lemon:'yellow', orange:'orange'] as HashBiMap }
assert fruit.inverse().yellow == 'lemon'

Resources