How to represent object** in Java with graalvm native image? - graalvm

I'm consuming a C library in Java with GraalVm and I have this function I don't know how to implement:
interfaces_t** tt_full_list_iface();
This is my interfaces_t struct in Java
#CStruct(value = "interfaces_t")
public interface InterfacesT extends PointerBase {
#CField("name")
CCharPointer getName();
#CField("name")
void setName(CCharPointer name);
#CField("description")
CCharPointer getDescription();
#CField("description")
void setDescription(CCharPointer description);
#CField("friendly_name")
CCharPointer getFriendlyName();
#CField("friendly_name")
void setFriendlyName(CCharPointer friendlyName);
}
And my question is: How can I implement the native function that returns this struct?
#CFunction("tt_full_list_iface")
public static native InterfacesT(?) getFullListOfInterfaces();

Related

How can I hide some parameters from C DLL function on JNA Wrapper side?

I've successfully wrapped a C DLL library using JNA.
As I'm not the owner of the C development part, I would like to hide
some parameters of a C function that I've wrapped on java side.
To be more precise my java code is as follows :
public interface IJNALibrary extends Library {
// INIT FUNCTION
public int initFunction(int firstValue, int secondValue, int thirdValue);
}
On the C side I have in the *.h file :
extern "C" CSAMPLE_API int initFunction (
unsigned firstValue,
unsigned secondValue,
unsigned thirdValue);
My purpose is to directly set secondValue and thirdValue parameters to 1 and thus hide those parameters to the java API user.
I don't want the user to know that he could change the values of those parameters.
In fact I would like to have something like :
public interface IJNALibrary extends Library {
// INIT FUNCTION
public int initFunction(int firstValue);
}
and initFunction(int firstValue) calls initFunction(int firstValue, int secondValue, int thirdValue) from the C DLL part.
But this has to be done inside the java Wrapper and not from the code which calls the java Wrapper.
I'm afraid that It cannot be possible, is it?
Unless I create another C DLL (with public int initFunction(int firstValue) function) which calls the first C DLL(which embed initFunction(int firstValue, int secondValue, int thirdValue).But I would rather do it on the java side in order not to have manage 2 C DLLs.
See also below the Sample.java file which calls the mapped method defined in IJNALibrary interface.
public class Sample {
static IJNALibrary IJNAFunctions;
public static void main(String[] args) throws IOException {
System.setProperty("jna.library.path", "./librayPath");
// LOADING LIBRARY
IJNAFunctions = (IJNALibrary) Native.load("c", IJNALibrary.class);
int firstValue = 1;
int secondValue = 2;
int thirdValue = 3;
int initReturn = IJNAFunctions.initFunction(firstValue, secondValue, thirdValue);
}
}
Thanx for your help.
It depends on what you want to archive. If you want to make it easier for users to call the init, this is an option (demonstrated using gethostname from libc), which uses a Java 8 feature, which allows adding default methods to interfaces:
public class TestDefaultMethod {
public static interface LibC extends Library {
LibC INSTANCE = Native.load("c", LibC.class);
// Original binding of method
int gethostname(byte[] name, int len);
// Helper method to make it easier to call gethostname
default String gethostname() {
byte[] result = new byte[255];
LibC.INSTANCE.gethostname(result, result.length);
return Native.toString(result);
}
}
public static void main(String[] args) {
// Usage
System.out.println(LibC.INSTANCE.gethostname());
}
}
Java developers normally don't arrays to functions, which fill them and a java developer would never pass the length of the array in a separate parameter. These are artifacts of the C nature of the function. In the wrapped function an array is allocated, the native call done and the array then unwrapped. All the ugly C specialties are hidden in the default method.
If you don't want to expose the method on java at all (be warned, if your users can access the JNA library, they can circumvent your protections!), you can use a function pointer directly:
public class TestDefaultMethod {
public static interface LibC extends Library {
NativeLibrary libc = NativeLibrary.getInstance("c");
LibC INSTANCE = Native.load("c", LibC.class);
default String gethostname() {
byte[] result = new byte[255];
libc.getFunction("gethostname").invokeInt(new Object[] {result, result.length});
return Native.toString(result);
}
}
public static void main(String[] args) {
System.out.println(LibC.INSTANCE.gethostname());
}
}
Same idea as above, the default method will hide the ugly parts. In this case though the function is not accessed through the managed INSTANCE, but access through the function pointer directly.

Dependency Injection in Apache Storm topology

Little background: I am working on a topology using Apache Storm, I thought why not use dependency injection in it, but I was not sure how it will behave on cluster environment when topology deployed to cluster. I started looking for answers on if DI is good option to use in Storm topologies, I came across some threads about Apache Spark where it was mentioned serialization is going to be problem and saw some responses for apache storm along the same lines. So finally I decided to write a sample topology with google guice to see what happens.
I wrote a sample topology with two bolts, and used google guice to injects dependencies. First bolt emits a tick tuple, then first bolt creates message, bolt prints the message on log and call some classes which does the same. Then this message is emitted to second bolt and same printing logic there as well.
First Bolt
public class FirstBolt extends BaseRichBolt {
private OutputCollector collector;
private static int count = 0;
private FirstInjectClass firstInjectClass;
#Override
public void prepare(Map map, TopologyContext topologyContext, OutputCollector outputCollector) {
collector = outputCollector;
Injector injector = Guice.createInjector(new Module());
firstInjectClass = injector.getInstance(FirstInjectClass.class);
}
#Override
public void execute(Tuple tuple) {
count++;
String message = "Message count "+count;
firstInjectClass.printMessage(message);
log.error(message);
collector.emit("TO_SECOND_BOLT", new Values(message));
collector.ack(tuple);
}
#Override
public void declareOutputFields(OutputFieldsDeclarer outputFieldsDeclarer) {
outputFieldsDeclarer.declareStream("TO_SECOND_BOLT", new Fields("MESSAGE"));
}
#Override
public Map<String, Object> getComponentConfiguration() {
Config conf = new Config();
conf.put(Config.TOPOLOGY_TICK_TUPLE_FREQ_SECS, 10);
return conf;
}
}
Second Bolt
public class SecondBolt extends BaseRichBolt {
private OutputCollector collector;
private SecondInjectClass secondInjectClass;
#Override
public void prepare(Map map, TopologyContext topologyContext, OutputCollector outputCollector) {
collector = outputCollector;
Injector injector = Guice.createInjector(new Module());
secondInjectClass = injector.getInstance(SecondInjectClass.class);
}
#Override
public void execute(Tuple tuple) {
String message = (String) tuple.getValue(0);
secondInjectClass.printMessage(message);
log.error("SecondBolt {}",message);
collector.ack(tuple);
}
#Override
public void declareOutputFields(OutputFieldsDeclarer outputFieldsDeclarer) {
}
}
Class in which dependencies are injected
public class FirstInjectClass {
FirstInterface firstInterface;
private final String prepend = "FirstInjectClass";
#Inject
public FirstInjectClass(FirstInterface firstInterface) {
this.firstInterface = firstInterface;
}
public void printMessage(String message){
log.error("{} {}", prepend, message);
firstInterface.printMethod(message);
}
}
Interface used for binding
public interface FirstInterface {
void printMethod(String message);
}
Implementation of interface
public class FirstInterfaceImpl implements FirstInterface{
private final String prepend = "FirstInterfaceImpl";
public void printMethod(String message){
log.error("{} {}", prepend, message);
}
}
Same way another class that receives dependency via DI
public class SecondInjectClass {
SecondInterface secondInterface;
private final String prepend = "SecondInjectClass";
#Inject
public SecondInjectClass(SecondInterface secondInterface) {
this.secondInterface = secondInterface;
}
public void printMessage(String message){
log.error("{} {}", prepend, message);
secondInterface.printMethod(message);
}
}
another interface for binding
public interface SecondInterface {
void printMethod(String message);
}
implementation of second interface
public class SecondInterfaceImpl implements SecondInterface{
private final String prepend = "SecondInterfaceImpl";
public void printMethod(String message){
log.error("{} {}", prepend, message);
}
}
Module Class
public class Module extends AbstractModule {
#Override
protected void configure() {
bind(FirstInterface.class).to(FirstInterfaceImpl.class);
bind(SecondInterface.class).to(SecondInterfaceImpl.class);
}
}
Nothing fancy here, just two bolts and couple of classes for DI. I deployed it on server and it works just fine. The catch/problem though is that I have to initialize Injector in each bolt which makes me question what is side effect of it going to be?
This implementation is simple, just 2 bolts.. what if I have more bolts? what impact it would create on topology if I have to initialize Injector in all bolts?
If I try to initialize Injector outside prepare method I get error for serialization.

Eclipse Scout Neon : code type not working

I have one List box and I would like to set code type of it.
I create new AbstractCodeType :
public class MyCodeType extends AbstractCodeType<String, String> {
private static final long serialVersionUID = 6808664924551155395L;
public static final String ID = null;
#Override
public String getId() {
return ID;
}
#Order(10.0)
public static class UnknownCode extends AbstractCode<String> {
private static final long serialVersionUID = -1307260056726644943L;
public static final String ID = "Unknown";
#Override
protected String getConfiguredText() {
return TEXTS.get("Unknown");
}
#Override
public String getId() {
return ID;
}
}
}
and I set this code type in list box :
#Override
protected Class<? extends ICodeType<?, String>> getConfiguredCodeType() {
return MyCodeType.class;
}
But doesn't work. It return empty box.
While I was debugging I noticed that in AbstractListBox.class in initConfig method it call this code type and set code type in m_lookupCall inside setCodeTypeClass. Then inside execLoadTableData, it get call but this call return empty array when called call.getDataByAll().
I suspect that converting between code type and Lookup call does not work properly.
EDIT
I try to debug where is the problem and if follow the path :
initConfig() -> CodeLookupCall.newInstanceByService(m_codeTypeClass); (line 581)
and if you look inside CodeLookupCall ;
getDataByAll() in line 221 `resolveCodes(v)` -> BEANS.opt(m_codeTypeClass) -> bean.getInstance() -> m_producer.produce(this) -> return (T) getCache().get(createCacheKey(type));
This is in class CodeService.class in line 97 :
Class<T> type is right class and createCacheKey(type) return not null object but then getCache().get(...) return null. From this point on everything is null (what is reasonable regarding that getCodeType return null.)
This is what I found out while debugging, if it helps someone to figure out what is wrong.
It looks like your codetype class is not found by the bean manager. CodeService only finds CodeTypes in its classpath (accessible in the server).
-> You might need to move your class to the shared project.
You can find examples for code types in the contacts demo application:
https://github.com/BSI-Business-Systems-Integration-AG/org.eclipse.scout.docs/tree/releases/5.2.x/code/contacts
I tested your code snippet with Eclipse Scout Neon M4 and I could reproduce your described error.
However, it seems that this bug has been fixed with Scout Neon M5. So I suggest that you upgrade to the latest milestone version, which is recommended anyway.

Converting a Foo into a Foo.ByValue?

I am integrating with an aged lm_sensors library using JNA and JNAerator, with a view to creating MBeans for each of the temperature sensors inside my box. Firstly I'm calling this method:
// C edition
const sensors_chip_name *sensors_get_detected_chips(int *nr);
// Java edition
sensors_chip_name sensors_get_detected_chips(IntByReference nr);
.. which works just fine. Subsequently I need to call:
// C edition
int sensors_get_feature(sensors_chip_name name, int feature, double *result);
// Java edition
int sensors_get_feature(sensors_chip_name.ByValue name, int feature, DoubleByReference result);
.. what I am lacking is how to take the result of sensors_get_detected_chips and pass it by value to the 1st argument of sensors_get_feature.
The following allows a ByValue version of the struct to be initialized from the base class.
public class sensors_chip_name extends Structure {
public class ByValue extends sensors_chip_name implements Structure.ByValue {
public ByValue(sensors_chip_name orig) {
this(orig.getPointer().share());
}
public ByValue(Pointer p) {
super(p);
}
public ByValue() { }
}
public sensors_chip_name() { }
public sensors_chip_name(Pointer p) {
super(p);
read();
}
}

jna: pass a string from C# to Java

I am using Unamanged dependencies (RGiesecke.DllExport.DllExport) and jna in a small C# function that should return a string consumed within another now java function.
Following the jna suggestions for mapping i crafted the code below:
My C# code:
[RGiesecke.DllExport.DllExport]
public static unsafe char* Test(string id)
{
unsafe
{
fixed (char *s = "test passed")
{
return s;
}
}
}
Java side:
public interface ITest extends Library{
public String Test(String id);
}
public static void main(String[] args) {
ITest nativeExample= (ITest)Native.loadLibrary("C:/native/JavaLib.dll", ITest.class);
String s = nativeExample.Test("id");
System.out.println(s);
}
So, all that is printed, is 't', because I bet all is being transmitted is the address to s[0].
Has anyone had luck mapping strings from C# to java through jna?
Plain strings in the C# code throws errors.
Have you tried returning a string instead of char? or changing char *s to char s[]

Resources