Integrating java and .net dll using JNI - java

I am doing a small project it is a interoperability of java and .net dll.
Focus:
I just have a java file which calls the .net dll which is created by using C# and CPP and MCPP..
The program is just a hello world Program..
I just refer the below mentioned sites.
http://www.codeproject.com/Articles/378826/How-to-wrap-a-Csharp-library-for-use-in-Java
http://www.codeproject.com/Articles/13093/C-method-calls-within-a-Java-program
Finally I just get some ideas and finally did this with some errors.
Coding:
#using "mscorlib.dll"
#using "CSharpHelloWorld.netmodule"
using namespace System;
public __gc class HelloWorldC
{
public:
// Provide .NET interop and garbage collecting to the pointer.
CSharpHelloWorld __gc *t;
HelloWorldC() {
t = new CSharpHelloWorld();
// Assign the reference a new instance of the object
}
// This inline function is called from the C++ Code
void callCSharpHelloWorld() {
t->displayHelloWorld();
}
};
Errors:
Error 1 error C4980: '__gc' : use of this keyword requires /clr:oldSyntax command line option
Error 2 error C3699: 'interior_ptr' : cannot use this indirection on type 'CSharpHelloWorld'
Error 3 error C2750: 'CSharpHelloWorld' : cannot use 'new' on the reference type; use 'gcnew' instead
Error 4 error C2440: '=' : cannot convert from 'CSharpHelloWorld *' to 'CSharpHelloWorld ^' 11 WindowsComponentProject
Error 5 error C2011: 'HelloWorldC' : 'class' type redefinition 6 WindowsComponentProject
Error 6 error C3699: '*' : cannot use this indirection on type 'HelloWorldC' 18 WindowsComponentProject
Error 7 error C2750: 'HelloWorldC' : cannot use 'new' on the reference type; use 'gcnew' instead 18 WindowsComponentProject
Error 8 error C2440: 'initializing' : cannot convert from 'HelloWorldC *' to 'HelloWorldC ^' 18 WindowsComponentProject
Error 9 error C2027: use of undefined type 'HelloWorldC' 21 WindowsComponentProject
Error 10 error C2227: left of '->callCSharpHelloWorld' must point to class/struct/union/generic type 21 WindowsComponentProject
I just seek some sites for the solution to change the properties of CLR but it doesn't works kindly help me over it.. thanks in advance !!!

You are using old Managed C++ syntax.
New one is called C++/CLI.
You create a reference type by prefixing the class declaration with ref keyword. Use ^ to declare a reference variable as in CSharpHelloWorld^ t.
gcnew is what you use to create an object in managed heap.
You should modify your class as shown below.
using namespace System;
public ref class HelloWorldC {
public:
// Provide .NET interop and garbage collecting to the pointer.
CSharpHelloWorld^ t;
HelloWorldC() {
t = gcnew CSharpHelloWorld();
// Assign the reference a new instance of the object
}
// This inline function is called from the C++ Code
void callCSharpHelloWorld() {
t->displayHelloWorld();
}
};

Related

Error in ColdFusion Javacast array to class from loadPaths

I am trying to use Elasticsearch's Java API.
I am trying to create a RestClientBuilder.
Host=createObject("java", "org.apache.http.HttpHost").init(variables.HostName, variables.Port);
Node=createObject("java", "org.elasticsearch.client.Node").init(Host);
RestClient=createObject("java", "org.elasticsearch.client.RestClient").builder(Javacast("org.elasticsearch.client.Node[]", [Node])).build();
I get the error
Cannot convert the value to Java array because type org.elasticsearch.client.Node is unknown.
Also if I just try to use:
RestClient=createObject("java", "org.elasticsearch.client.RestClient").builder(Javacast("org.apache.http.HttpHost[]", [Host]));
I get the following error
Either there are no methods with the specified method name and
argument types or the builder method is overloaded with argument types
that ColdFusion cannot decipher reliably. ColdFusion found 0 methods
that match the provided arguments. If this is a Java object and you
verified that the method exists, use the javacast function to reduce
ambiguity.
This I assume is because ColdFusion doesn't play nicely with varargs
I found a workaround using this method
https://www.bennadel.com/blog/1980-tojava---a-coldfusion-user-defined-function-for-complex-java-casting.htm
I believe there is a bug with Javacast and javaSettings loadPaths not being used.
coldfusion.runtime.Cast$UnknownTypeException: Cannot convert the value
to Java array because type org.elasticsearch.client.Node is unknown.
at coldfusion.runtime.Cast.toJavaArray(Cast.java:1602)
Additionally if I try to perform the actiuons that the UDF takes
local.javaClass = createObject("java", "org.apache.http.HttpHost");
local.HostArrayReflect = createObject("java", "java.lang.reflect.Array");
local.HostArray = local.HostArrayReflect.newInstance(
local.javaClass.GetClass()
, JavaCast( "int", ArrayLen(local.Hosts))
);
for (i=0; i LT ArrayLen(local.Hosts); i=i+1) {
local.HostArrayReflect.Set(local.HostArray, JavaCast("int", i), local.Hosts[i]);
}
I get the error
An exception occurred while instantiating a Java object. The class
must not be an interface or an abstract class. If the class has a
constructor that accepts an argument, you must call the constructor
explicitly using the init(args) method. Error :
org.apache.http.HttpHost
java.lang.NoSuchMethodException: org.apache.http.HttpHost.() at
java.lang.Class.getConstructor0(Class.java:3082) at
java.lang.Class.newInstance(Class.java:412) at
coldfusion.runtime.java.JavaProxy.createObjectWithDefaultConstructor(JavaProxy.java:209)
at coldfusion.runtime.java.JavaProxy.invoke(JavaProxy.java:92)
This happens when I try to run getClass(), but in the UDF there is no issue. A coworker tried to run this on Lucee and it seems to have worked, so I believe there is a bug in CF related to this.

Facing some unknown issue some backend jvm internal error

I am facing some unknown issue looks like it is some internal compiler error:
these are the error when building apk:
Error:org.jetbrains.kotlin.codegen.CompilationException: Back-end (JVM) Internal error: Couldn't transform method node: doResume (Ljava/lang/Object;Ljava/lang/Throwable;)Ljava/lang/Object;:
Error:org.jetbrains.org.objectweb.asm.tree.analysis.AnalyzerException: Error at instruction #375 L0: Incompatible stack heights
Error:org.jetbrains.org.objectweb.asm.tree.analysis.AnalyzerException: Incompatible stack heights
Any help would be appreciated.
After struggling for a long time I found the solution, the code which causes the problem is this:
if (investorType=="Institutional")
{linSignUp
if (firmName.isEmpty()) {
There is a problem in first if block which a linSignUp a reference of linear layout which accidentally placed here, which should not be here.
So the View just here alone with no use, when I removed it, the build generated successfully.
This was one of the most frustrating errors to track down.
Here is the error I was getting:
java.lang.IllegalStateException: Backend Internal error: Exception during code generation
Cause: Back-end (JVM) Internal error: wrong code generated
org.jetbrains.kotlin.codegen.CompilationException Back-end (JVM) Internal error: Couldn't transform method node:
.....
If your stack trace further on is related to views and strings, the main culprit for me was that the xml view id was too long.
This name caused the error: team_management_players_recycler_view_layout
I reduced it to this: team_man_players_recycler_layout
BOOM ERROR WAS GONE!
Hope this helps someone else out!
I had the same error in kotlin 1.3.72 and the code that was causing it was a recursive suspend function contained in a suspend function:
suspend fun function1(){
suspend fun internalFun(){
// does something
internalFun() //<-- this was causing the problem
}
internalFun()
}
I fixed by rearranging the code in such a way that i hadn't to call internalFun() inside itself.
I don't know if the fact that they were suspend functions was relevant.
Error message: "e: org.jetbrains.kotlin.codegen.CompilationException: Back-end (JVM) Internal error: wrong bytecode generated"
In my case, I used runBlocking{} in one of MainViewModel.kt's methods.
The app was compiling successfully with runBlocking{} (which I shouldn't use anyway)) until I changed the name of a parameter in that method.
I replaced runBlocking{} with viewModelScope.launch {} in order to get ride of this error message.
In case this helps others in the future, my issue was due to using my custom extension:
suspend operator fun <T> MutableLiveData<T>.plusAssign(newValue: T) = ...
It was used like this:
init {
job = GlobalScope.launch {
while (true) {
delay(1000)
foo += bar // This is the error.
}
}
}
Using it like this, is however, completely fine:
suspend fun refreshNextJob() {
foo += bar
}
Not sure why this happens, but maybe this will help someone later.
In my case I got this exception:
java.lang.IllegalStateException: Backend Internal error: Exception
during code generation Cause: Back-end (JVM) Internal error: wrong
code generated org.jetbrains.kotlin.codegen.CompilationException
Back-end (JVM) Internal error: Couldn't transform method node: getS
()Ljava/lang/String;: #Lorg/jetbrains/annotations/NotNull;() //
invisible L0
LINENUMBER 9 L0
NEW com/example/GsonConverter
DUP
INVOKESPECIAL com/example/GsonConverter. ()V
ASTORE 1 L1
LINENUMBER 10 L1 ...
Cause: UTF8 string too large Element is unknownThe root cause was
thrown at: ByteVector.java:246 Cause: Back-end (JVM) Internal error:
Couldn't transform method node: getS ()Ljava/lang/String;:
#Lorg/jetbrains/annotations/NotNull;() // invisible L0 ...
Cause: UTF8 string too large Element is unknownThe root cause was
thrown at: ByteVector.java:246 File being compiled at position: (8,5)
in
C:/Users/user/AndroidStudioProjects/MyApplication03/app/src/main/java/com/example/myapplication/ATest.kt
The root cause was thrown at: TransformationMethodVisitor.kt:92 File
being compiled at position:
file://C:/Users/user/AndroidStudioProjects/MyApplication03/app/src/main/java/com/example/myapplication/ATest.kt
The root cause was thrown at: FunctionCodegen.java:1043 ...
Cause: UTF8 string too large Element is unknownThe root cause was
thrown at: ByteVector.java:246 ...
I removed a class ATest from an application, but it didn't help. A problem was in a constant string about 80 Kb (JSON).
In my case I just forgot to add method call when typed view name.
img_my_best_image
Instead of
img_my_best_image.show()

Why does Java 8's Nashorn engine in strict mode throw a java.lang.ClassCastException when calling apply() and passing the arguments object directly?

When I call eval (in strict mode) on a nashorn engine with the following script I get an exception:
var yfunc = function () {
(null).apply(null, arguments);
};
yfunc();
I've truncated my personal situation heavily. The "(null)" on line 2 can be replaced with anything between parenthesis or a local variable, either way just something that shouldn't throw a compile error, and it will yield the same result.
The issue seems to be explicitly that "arguments" is passed directly as the second argument of calling a method called "apply". Any of the following changes will undo the thrown exception:
Putting "arguments" in a variable first (but simply wrapping it in parenthesis doesn't work!)
Calling something other than apply
Passing "arguments" in a different argument slot when calling apply
Calling print() (with or without passing any arguments) as a preceding line of code inside yfunc() (weird huh?)
Defining more than 0 parameters for yfunc()
Binding yfunc first and then calling the bound method
Calling yfunc via Function.apply (not so much with Function.call!)
The Exception thrown is this:
Exception in thread "main" java.lang.ClassCastException: Cannot cast jdk.nashorn.internal.runtime.Undefined to jdk.nashorn.internal.runtime.ScriptFunction
at java.lang.invoke.MethodHandleImpl.newClassCastException(MethodHandleImpl.java:361)
at java.lang.invoke.MethodHandleImpl.castReference(MethodHandleImpl.java:356)
at jdk.nashorn.internal.scripts.Script$\^eval\_.:program(<eval>:4)
at jdk.nashorn.internal.runtime.ScriptFunctionData.invoke(ScriptFunctionData.java:637)
at jdk.nashorn.internal.runtime.ScriptFunction.invoke(ScriptFunction.java:494)
at jdk.nashorn.internal.runtime.ScriptRuntime.apply(ScriptRuntime.java:393)
at jdk.nashorn.api.scripting.NashornScriptEngine.evalImpl(NashornScriptEngine.java:449)
at jdk.nashorn.api.scripting.NashornScriptEngine.evalImpl(NashornScriptEngine.java:406)
at jdk.nashorn.api.scripting.NashornScriptEngine.evalImpl(NashornScriptEngine.java:402)
at jdk.nashorn.api.scripting.NashornScriptEngine.eval(NashornScriptEngine.java:155)
at javax.script.AbstractScriptEngine.eval(AbstractScriptEngine.java:264)
When I call this method with an owner, the exception thrown changes. Example code:
var yfunc = {
method: function () {
(null).apply(null, arguments);
}
};
var x = yfunc.method();
Then the thrown exception looks like this:
Exception in thread "main" java.lang.ClassCastException: Cannot cast jdk.nashorn.internal.scripts.JO4 to jdk.nashorn.internal.runtime.ScriptFunction
at java.lang.invoke.MethodHandleImpl.newClassCastException(MethodHandleImpl.java:361)
at java.lang.invoke.MethodHandleImpl.castReference(MethodHandleImpl.java:356)
at jdk.nashorn.internal.scripts.Script$\^eval\_.:program(<eval>:5)
at jdk.nashorn.internal.runtime.ScriptFunctionData.invoke(ScriptFunctionData.java:637)
at jdk.nashorn.internal.runtime.ScriptFunction.invoke(ScriptFunction.java:494)
at jdk.nashorn.internal.runtime.ScriptRuntime.apply(ScriptRuntime.java:393)
at jdk.nashorn.api.scripting.NashornScriptEngine.evalImpl(NashornScriptEngine.java:449)
at jdk.nashorn.api.scripting.NashornScriptEngine.evalImpl(NashornScriptEngine.java:406)
at jdk.nashorn.api.scripting.NashornScriptEngine.evalImpl(NashornScriptEngine.java:402)
at jdk.nashorn.api.scripting.NashornScriptEngine.eval(NashornScriptEngine.java:155)
at javax.script.AbstractScriptEngine.eval(AbstractScriptEngine.java:264)
I've reproduced the issue so far on specifically these environments:
windows 7 64bit -> jdk 1.8.0_60 64bit
windows 8 64bit -> jdk 1.8.0_131 64bit
I can't seem to find anything on the internet about similar issues. Do I need to report this to Oracle/OpenJDK?
Minor update
Added items 6 and 7 to list of "following changes will undo the thrown exception".
Final update
Bug filed: JDK-8184720
Yes, it appears to be a bug. Please file a bug.

Convert a stream into a list

I want to convert a stream into a list. To do so I have tried this code :
try(Stream<String> stream = Files.lines(Paths.get(args[0]))) {
List<String> lines = stream.collect(Collectors.toList());
}
But then the compiler tell me that :
Type mismatch: cannot convert from List<Object> to List<String>
Also I've tried this way :
try(Stream<String> stream = Files.lines(Paths.get(args[0]))) {
List<String> lines = Stream.of(stream).collect(Collectors.toList());
}
But then I have this error :
This static method of interface Stream can only be accessed as Stream.of
which happen every time, whenever I use the Stream.of methods.
Can someone help me out, please?
It's seems that you use java compiler language level lower than 8.
Try compiling from command line with
javac -source 8
Also check your language level project setting in IDE.
For example, output from IDEA 2016 hides info about used language level, but provide info about javac version
Information:Using javac 1.8.0_101 to compile java sources
Information:java: Errors occurred while compiling module 'demo_04'
Information:8/1/16 2:13 PM - Compilation completed with 1 error and 0 warnings in 1s 403ms
/tmp/1/src/JavaStreamExample.java
Error:(16, 49) java: incompatible types: java.util.List<java.lang.Object> cannot be converted to java.util.List<java.lang.String>

How to call String[][] in R using rjava

I am preparing an R wrapper for a java code that I didn't write myself (and in fact I don't know java). I am trying to use rJava for the first time and I am struggling to get the .jcall right.
Here is an extract of the java code for which I write a wrapper:
public class Model4R{
[...cut...]
public String[][] runModel(String dir, String initFileName, String[] variableNames, int numSims) throws Exception {
[...cut...]
dir and initFileName are character strings for the directory and file name with initial conditions, variable names is a list of character strings that I would write like this in R: c("var1", "var2", "var3", ...) and can be of length from one to five. Finally, numSim is an integer.
Here is my tentative R code for a wrapper function:
runmodel <- function(dir, inFile, varNames, numSim){
hjw <- .jnew("Model4R")
out <- .jcall(hjw, "[[Ljava/lang/String", "runModel", as.character(dir), as.character(inFile), as.vector(varNames), as.integer(numSim))
return(out)
}
The error in R is:
Error in .jcall(hjw, "[[Ljava/lang/String", "runModel", as.character(dir),
: method runModel with signature (Ljava/lang/String;Ljava/lang/String;Ljava/lang/String;II)[[Ljava/lang/String not found
I suspect that the JNI type isn't correct for String[][]. Anyhow, any help that could direct me towards a solution would be welcome!
You're missing a semicolon at the end of the JNI for String[][] - it should be "[[Ljava/lang/String;". Also, I think you need to call .jarray instead of as.vector on varNames. The R error is telling you that rJava thinks the class of the third argument is Ljava/lang/String; instead of [Ljava/lang/String;.

Categories

Resources