How to write a java varg function in clojure? - clojure

In Java, a varg function can be written like this:
public static void foo(int ... a)
{
// method body
}
It gets called in Java like this:
<OBJ>.foo(1, 2, 3);
and it gets called in Clojure like this:
(<OBJ>/foo (int-array [1 2 3])
Is it possible to write foo in Clojure so that it gets called in Java as a varg function?

Unfortunately, there is no option to make Java-style varargs methods (that is, methods that accept arrays and have the VARARGS (0x80) bit set to true).
Instead, you can either make a function that accepts an array (and write a varargs wrapper around it in Java, if you need varargs) or make a Clojure's [&rest] function and .invoke() it with varargs.

Related

Does Clojure repeatedly initiate new class(object) for every function call?

What is the low-level operation underneath of the function call?
What kind of Java code will be generated when we call a function from Clojure?
I would like to know the details of it so I can write more performance focused code.
In clojure, anything invoked as a function must implement the clojure.lang.IFn interface. This interface includes a overloaded method called invoke. Functions are first-class in Clojure, so when you say (def square (fn [x] (* x x))), square is assigned to the instance of a class that implements IFn.
So to sum up: invoking a function in Clojure incurs the cost of calling a method on an object.
Clojure functions implement the IFn interface, which provides the invoke() call with numerous different signatures. Unless you're passing more than 20 arguments, in which case a variadic signature is in use, it's just as fast as any other method invocation in the JVM.

Clojure - more idiomatic to return a closure, or partially apply the function?

I'm using an external library, and passing it a function that I write. Something like this, for example:
(ext-func my-func) ...
my-func needs to be given some data to do computation. The way I see it, I have two basic choices:
1) Write my-func in such a way that it accepts my data, and returns a function, which will then have the data bound to it via closure when the external library calls it. For example:
(defn my-func
[mydata]
(fn []
(... access to mydata via closure ... )))
(ext-func (my-func somedata))
2) Do not return a function from my-func, but bind data to it when I pass it to ext-func:
(defn my-func
[mydata]
(... evaluate, use mydata, etc.))
(ext-func (partial my-func somedata))
I suppose which one to use could be answered by how I intend to use the function otherwise. If I'm going to be using it other places, I may prefer not to return a function, for example. But, all other things being equal...
...which of these is the more idiomatic approach?
partial is just sugar to create the anonymous function. Check out it's source. So, effectively they're equivalent. Take your pick. Neither is more idiomatic, just a matter of personal preference.

call Lua function from C++ conditionally

I am using Lua to write scipts and embed them in C++. I use LuaBridge in this process.
In my Lua script, I have some variables which need to be retrieved at first for usage in C++, besides, I have a very simple function:
run = function()
print ("state is on!")
end
This function, however, is only called under a specific condition. i.e. only called when a "true" is obtained from C++ codes after a series of complicated calculations.
Limited by my Lua and LuaBridge knowledge, what I know is: after I do
loadscript(L, "script.lua")
lua_pcall(L,0,0,0)
I can read out variables and functions from Lua script by using
LuaRef blabla = getGlobal(L, "blabla")
But now, I need to read out variables and use them at first, then in a member function
LuaRunner::LuaRun(){}
defined in a separate C++ class
class LuaRunner
the condition will be obatined and this run() function will be called if the condition is "true". It would be best to call this run() function right in the C++ member function
LuaRunner::LuaRun(){}
due to restriction of further processing.
Therefore, I was wondering whether this would be possible:
Read out the function using
LuaRef run = getGlobal(L, "run")
together with other variables at the beginning and "save" this run() function somewhere in C++ codes (perhaps as a class member function), and then the run() function can be called later on by a pointer or an object in the same class. Would this be possible? If possible, how to do it? Or any other good ideas?
It's possible to store luabridge::LuaRef's in C++ to call them later just as you normally call any other function. Though sometimes there's no need to store LuaRef's anywhere. Once you load the script, all functions stay in your lua_State, unless you set them to nil or override them by loading another script which uses the same names for functions. You can get them by using getGlobal function. If your Lua function takes arguments, you can pass them, using LuaRef's operator() like this:
if(...) { // your call condition
LuaRef f = getGlobal(L, "someFunction");
f(arg1, arg2, ...); // if your function takes no arguments, just use f();
}

JNI: Calling a Java method in C++ with an object as argument

I'm new to JNI and have a Java program given, from which I want to call methods in C++.
I have an ObjectA implemented in Java. I receive its classID like this in C++:
jclass cls = env->FindClass("myPackages/ObjectA");
Now I have the method funcA given in Java. funcA accepts an Object of the type ObjectA as an argument and returns an integer. The declaration in Java looks like this:
public int funcA( ObjectA obj);
Now I want to get the methodID of funcA in C++. The problem is, I don't know how to specify which parametertype the method gets. I know that I have to write L fully-qualified-class ; to pass Objects like a String, but how do I do this, when the objects are not from official javalibraries but objects I created?
I tried this, but it obviously didn't work:
jmethodID jfuncA = env->GetMethodID(cls, "funcA", "(Lcls;)I");
All I got as a response is, that the Method was not found. So what do I have to write instead of (Lcls;)? Or is this impossible?
Any idea is useful!
Run javap -s on your compiled Java class and use exactly what it tells you as the signature of the native method. Cut and paste. Don't waste your time trying to figure it out for yourself when you have a tool that is never wrong.

std::tr1::function assignment and binding

I'm trying to learn how to best use the std::function and the std::bind facilities
in the standard library - I'm interested in the TR1 versions, as that's what I
have available for now and I'm not aware of the differences, if any, between the TR1 implementations and the C++11 ones.
So for the sake of the exercise I've set up to construct a simple let's say "dispatcher".
What I want is to be able to execute any function from the dispatcher based on some decisions taken later at runtime. I set up my class to have a general function data
member like so:
class PoorDispatcher
{
...
private:
std::tr1::function<void()> m_f;
}
Then I assign to the data member the function I really want to call, similar to the below
...
m_f = std::tr1::bind(some_func, param1, param2, param3);
...
// then the call
m_f(); // SUCCESS
The above allows me to call successfully the function I want but I'm not sure it's the right thing to do. The questions:
Is the above usage scenario "sane"? Are there any better alternatives?
The above method poses a problem when trying to bind to a function which returns something. How can I retrieve the return value? (In my silliness I tired to cast the function objects without much success)
The template argument to std::function is the actual function type. void() means a function which takes no arguments and returns no value.
If you want to store a function that returns a value you have to create a new function object. Or if you are not sure if the function will return something, use boost.optional.