I'm writing an application that uses the LuaJ library to load and interpret Lua code. I have the following code which is an OneArgFunction.
static class addCommand extends OneArgFunction {
public LuaValue call(LuaValue x) {
if(x.isfunction()) {
LuaClosure closure = x.checkclosure();
closure.call();
return LuaValue.valueOf(true);
} else {
return LuaValue.valueOf(false);
}
}
}
What I need is to convert the LuaClosure to a Java method and invoke it. How could I do this?
Sorry if this question is hard to understand, as I'm not good at English.
Related
I'm using a native library coded in C or C++, after a lot of multiple tests i successed to make it work, but i'm not sure if what i do correspond to the correct coding rules, and some parts are not clear for me.
So my question is : could you confirm and complete what i understood.
Thanks
the C prototype function is:
typedef void (*pfHook) (const char *pText);
and the function to set the callback function is:
short LogHookEx(void (*pfHook) (const char*));
So i created an interface for my native dll like that:
So if i understood "interface pfHookCallback" correspond to the C prototype function and "sCscSetApiLogHookEx" is a classic method from my native dll.
public interface Reader extends Library {
Reader INSTANCE = (Reader) Native.load((Platform.isWindows() ? "ReaderDll" : "c"),
Reader.class);
interface pfHookCallback extends Callback {
void invoke(String pText);
}
short LogHookEx(pfHookCallback pfHook);
}
The part that i understand less, is the part that i include in my "main":
public class Principal {
public static void main(String[] args) {
Reader.pfHookCallback pfHook = new Reader.pfHookCallback() {
public void invoke(String pText) {
System.out.println(pText);
}
};
res = Reader.INSTANCE.LogHookEx(pfHook);
To be more clear this callback function is used for tracing from an hardware device.
As described above, it's working, but it's not cleat for me.
And another question is , the goal of my code is to save the logs (so the pText string) into a file. Is there a best practice to do that, because if i create buffered writer, i don't know if it's good or not to do something like that:
public class Principal {
public static void main(String[] args) {
Reader.pfHookCallback pfHook = new Reader.pfHookCallback() {
public void invoke(String pText) {
bw.write(pText);
bw.close;
}
};
res = Reader.INSTANCE.LogHookEx(pfHook);
My question is i don't know if it's really good to open and close a file very quickly every time there is a log to be saved ?
I am developing an Eclipse RCP application and I recently started to use Groovy in it. So 99% of my code is still Java.
I read that it is possible to use Groovy to override and add methods to Java classes and I was able to test this by adding a method to the java.lang.String.
But this only works when I use the string in a Groovy class. The overridden method is not considered as being overridden in a Java class.
Here's some code:
/*
* This is a Java class
*/
public class CTabItem {
...
private API
...
public void setControl(Control control){
private API
}
}
/*
* This is also a Java class
*/
public class Control {
...
private API
...
}
/*
* This is also a Java class
*/
public class OtherClass {
...
private API
...
private void someMethodIDontKnow(){
Control control = new Control();
CTabItem tab = new CTabItem();
tab.setControl(control);
}
}
/*
* This is a Groovy class
*/
public class MyViewPart extends org.eclipse.ui.part.ViewPart {
....
public void createPartControl(Composite parent) {
/* parent (or the parent of parent) is a Control
which is set somewhere in a CTabItem to which
I don't get access */
}
}
I need to get the tab from the control. But since it's not me who instantiates MyViewPart, but some private API, I have no access to it.
Is there something Groovy could do for me here? Any suggestion or code is welcome. Thank you!
The short answer is: no, it's not possible if the code creating the object and calling the method is pure Java (i.e., non-Groovy) code. Groovy does its magic by intercepting all method calls on objects (both Java objects and Groovy objects) and using its ExpandoMetaClass to add the behavior. However, it can't change how pure Java code determines which method to call on a pure Java class. To see, run the following sample code:
// UseTheString.java (a pure Java class)
public class UseTheString {
public static void main(String[] arg) {
String s = "Hello world";
System.out.println(s);
System.out.println(s.substring(1));
ModifyStringClass.messWithMetaClasses(s);
System.out.println(s.substring(1));
}
}
and
// ModifyStringClass.groovy (a Groovy class)
class ModifyStringClass {
public static messWithMetaClasses(String t) {
java.lang.String.metaClass.substring = { int n -> "!" }
println(t.substring(1))
}
}
You'll get the output:
Hello world
ello world
!
ello world
As you can see, Groovy can override the method on a pure Java object if it is called from other Groovy code, but it can't change how the Java code uses it.
I want to add functions to the _G that can run Java code. I'm using Luaj and it can already run user written Lua code, but I want to add apis that'll allow the user to interact with the game world.
You make a class for each library function and one class to load the functions. You extend the appropriate class depending on how many arguments your function takes (up to three arguments, then you need to make your own FourArgFunction).
Here's trimmed down example code from MathLib.java file from the luaj source (to be found here: http://sourceforge.net/projects/luaj/files/latest/download):
This is what you need to load when you add you library.
public class MathLib extends OneArgFunction {
public static MathLib MATHLIB = null;
public MathLib() {
MATHLIB = this;
}
public LuaValue call(LuaValue env) {
LuaTable math = new LuaTable(0,30); // I think "new LuaTable()" instead of "(0, 30)" is OK
math.set("abs", new abs());
math.set("max", new max());
env.set("math", math);
env.get("package").get("loaded").set("math", math);
return math;
}
}
You load it like this:
globals.load(new MathLib());
Then you make subclasses of MathLib for each library function. For a function that takes one argument, here's an example:
abstract protected static class UnaryOp extends OneArgFunction {
public LuaValue call(LuaValue arg) {
return valueOf(call(arg.checkdouble()));
}
abstract protected double call(double d);
}
static final class abs extends UnaryOp {
protected double call(double d) {
return Math.abs(d);
}
}
You don't need the abstract class, you could make abs directly, but it will be obvious if you look at the source that it is more convinient to do it like this when you need to implement a lot of mathematical unary operations.
Here's an example for a function that takes a variable amount of arguments:
static class max extends VarArgFunction {
public Varargs invoke(Varargs args) {
double m = args.checkdouble(1);
for ( int i=2,n=args.narg(); i<=n; ++i )
m = Math.max(m,args.checkdouble(i));
return valueOf(m);
}
From Lua, you do: require('math') to load the lib and then something like math.abs(-123) to call a lib function.
I really recommend checking out the source of luaj if this is hard to grasp. Also, my trimmed down code is untested, so I'm not 100 % sure it works.
I've created a c# dll in visual studio 2008
the content of the c# dll is as given below:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
namespace hello
{
public class Class1
{
public static double addUp(double number, double Number)
{
return number + Number;
}
public static double minus(double number, double Number)
{
return number - Number;
}
}
}
and through java i've loaded the hello.dll using
System.loadLibrary("hello");
The java code is as given below:
package pkgnew;
import javax.swing.JOptionPane;
public class check
{
public static native double addUp(double number,double Number);
static
{
try
{
System.loadLibrary("hello");
System.out.println("SUCCESS");
}catch(Exception ex){ JOptionPane.showMessageDialog(null,"Required DLLs Not Found\n"+ex.getCause(),"Error Loading Libraries", JOptionPane.ERROR_MESSAGE);}
}
public static void main(String[] args)
{
new check().getval();
}
public void getval() {
try
{
double g=this.addUp(52.2, 51.3);
}catch(Exception y){System.out.println("ERROR IS:"+y);}
}
}
but the problem is that i'm getting output as:
OUTPUT
SUCCESS
Exception in thread "main" java.lang.UnsatisfiedLinkError: pkgnew.check.addUp(DD)D
at pkgnew.check.addUp(Native Method)
at pkgnew.check.getval(check.java:35)
at pkgnew.check.main(check.java:29)
Java Result: 1
Can anyone tell me why i'm getting this error....and why i'm not able to call the dll methods
I don't think you can call native extensions in Java without using JNI wrappers (or at least some library which translates to JNI under the hood). Have you tried out the frameworks/suggestions mentioned in this thread?
You cannot directly call C# dll in Java. There is a workaround. You'll have to first write a C++ managed class for C# code then create a of C++ dll and use it in java.
This link might be helpful.
I am developing with GWT and share a codebase with an Android developer. Some functions we want to share take speciffic arguments like "Drawable" under Android and "Image" under GWT.
Is it possible to use a preprocessor variable as in C++:
#ifdef ANDROID
public void DrawImg(Drawable img);
#elif GWT
public void DrawImg(Image img);
#endif
The solution we are testing is a Generic like this:
interface DrawImgInterf<T extends Object> {
public void DrawImg(T img);
}
However using a preproccesor variable seems better. Is there such a thing in Java?
No, there's nothing like that in normal Java. You could run a preprocessor of course, but that will make it painful to develop the code. (Anything like an IDE which expects the code to be "normal" Java is going to get confused.)
Have you considered using an interface instead, which abstracts out the common operations, and binds to the appropriate real type at execution time? That won't always work (as adding a proxy breaks situations where object identity is important) but in some cases it can be helpful.
No, there are no preprocessor variables in Java.
for such cases it is the best way to use a preprocessor
I used it for my J2ME developments http://code.google.com/p/java-comment-preprocessor/wiki/ExampleOfUsageForJ2ME
Java+ is a preprocessor which can perform substitution using resource bundles:
public static void
main(String[] args)
{
System.out.println({{
The answer,
my dearest,
is {{computeAnswer()}}.
}});
}
static String computeAnswer()
{
return {{my computed answer}};
}
References
java+.tgz
java+.dmg
Employing Visitor Pattern here, is making sense to me. For example,
interface ImageVisitor {
void visit(GWTImage image);
void visit(AndroidImage image);
}
interface IImage {
void accept(ImageVisitor visitor);
}
class GWTImage implements IImage {
..
public void accept(ImageVisitor visitor) {
visitor.visit(this);
}
..
}
class AndroidImage implements IImage {
..
public void accept(ImageVisitor visitor) {
visitor.visit(this);
}
..
}
class GWTImageVisitor implements ImageVisitor {
public void visit(GWTImage image) {
Image img = image.getImage();
..
}
}
class AndroidImageVisitor implements ImageVisitor {
public void visit(AndroidImage image) {
Drawable drawable = image.getDrawable();
..
}
}