简体   繁体   中英

How do you call C++ and\or Java functions from Python 2.7?

I am creating a Windows program that so far has a .bat file calling a .pyw file, and I need functions from Java and C++. How can I do this?(I don't mind creating a new batch or python file, and I already have the header file for the C++ section and a .jar file for my java components. (For Java I use Eclipse Java Mars, and it's Java 8u101)) Thanks!!!

This is rather simple for C++: you have to compile a library with the function, import it in Python and... call it! Python has a powerful ctypes module in the standard library to handle this kind of tasks.

Here is an example of loading print() function from hypothetical libc.dll .

from ctypes import *
libc = cdll.LoadLibrary("libc.dll")
>>> print(libc.time(None))
1150640792

Calling Java from Python is covered here: How to call a java function from python/numpy?

You can load C++ function and execute it from Python like BasicWolf explained in his answer. For Java, Jython might be a good approach. But then there's a problem - you will need to be dependent on Jython which is not up to date with the latest versions of Python. You will face compatibility issues with different libraries too.

I would recommend compiling your C++ and Java functions to create individual binaries out of them. Then execute these binaries from within Python, passing the arguments as command line parameters. This way you can keep using CPython. You can interoperate with programs written in any language.

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