简体   繁体   中英

Dynamic Link Library for Java/Python to access in C/C++?

A quick question that may seem out of the ordinary. (in reverse)

Instead of calling native code from an interpreted language; is there a way to compile Java or Python code to a .dll/.so and call the code from C/C++?

I'm willing to accept even answers such as manually spawning the interpreter or JVM and force it to read the .class/.py files. (is this a good solution?)

Thank you.

You can embed a Python interpreter in your C/C++ program.

http://docs.python.org/2/extending/embedding.html

With Java your probably want the Java Native Interface (which works in both directions).

http://en.wikipedia.org/wiki/Java_Native_Interface

gcj can compile most Java source to native code (linked with a libgcj shared library) instead of to JVM bytecode.

There are a number of Python projects that are similar, like shedskin , but none as mature or active.

Cython is similar, but not quite the same—it compiles modules written in a Python-like language into native C extension modules for CPython. But if you put that together with embedding Python in a C app , it gives you most of what you want. But you are still running a Python interpreter loop to tie all those compiled-to-C functions together.

You can also do the same thing with Java—embed the JVM into your app, use gcj to compile any parts you want to native code, while compiling other parts to bytecode, and using JNI to communicate between them.

And of course you can use Jython to embed your Python code into the JVM, which you can embed into your C program, and because you can use JNI directly from Jython any pair of the three languages can effectively talk to each other without going through the third.

The idea of spawning a JVM or a CPython interpreter as a subprocess, which I think you were suggesting in your question, also works just fine. However, the only interface you will have to it in that case will be the child process's stdin/stdout/stderr (or any pipes or sockets you create manually), which isn't as flexible as being able to call methods directly on objects, etc. (Then again, sometimes that extra indirection can be a good thing, forcing you to define a cleanly-separated API between your components.)

You can also look into Lua, while not as widely used as a lot of other scripting languages, it was meant to be embedded easily into executables. It's relatively small and fast. Just another option. If you want to call other languages from your c/c++ look into SWIG.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM