Invoke Python modules from Java

后端 未结 3 1573
心在旅途
心在旅途 2020-12-31 21:55

I have a Python interface of a graph library written in C - igraph (the name of library). My need is to invoke the python modules pertaining to this graph library from Java

相关标签:
3条回答
  • 2020-12-31 22:23

    You can use jep.getValue() to retrieve a value from script's global dictionary.

    There are caveats to that concerning scope levels in Python, so most people find it clearer to pass a Java class to python and set the return value in that instance in Python. After the script completes, the Java code will then have the result.

    For example:

    ==> Java

    class ReturnValueClass {
       public int scriptResult;
    };
    ReturnValueClass value = new ReturnValueClass();
    jep.set("retval", value);
    

    ==> Python

    # do something
    pass
    # write the return value
    retval.scriptResult = some_python_value
    

    ==> Java

    System.out.println(value.scriptResult);
    

    Hope that helps,

    Mike (I wrote Jep)

    0 讨论(0)
  • 2020-12-31 22:28

    Never tried it. But I recently stumbled on a project named Jepp that may be of interest to you.

    Jepp embeds CPython in Java. It is safe to use in a heavily threaded environment, it is quite fast and its stability is a main feature and goal.

    0 讨论(0)
  • 2020-12-31 22:37

    If you want to call C functions from Java, JNA (Java Native Access) is probably the way to go. JNA allows you to call functions in native libraries without having to write the C glue code (as you would have to when using JNI), and automatically maps between primitive data types in Java and C. A simple example might look like this:

    import com.sun.jna.Native;
    import com.sun.jna.Library;
    
    public class PrintfWrapper {
        public interface CLibrary extends Library {
            CLibrary INSTANCE = (CLibrary)Native.loadLibrary("c", CLibrary.class);
            void printf(String formatString, Object... args);
        }
    
        public static void main(String[] args) {
            CLibrary.INSTANCE.printf("Hello, world\n");
        }
    }
    

    However, things will get complicated with igraph because igraph uses many data structures that cannot be mapped directly into their Java counterparts. There is a project called JNAerator which should be able to generate the JNA source from igraph's header files, but I have never tried it and chances are that the results will still need some manual tweaking.

    Also note that a Java interface for igraph is being developed slowly but steadily and it might become useful in a few months or so.

    0 讨论(0)
提交回复
热议问题