从 Java 调用 C++ 函数

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/5626787/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-10-30 11:58:25  来源:igfitidea点击:

Calling C++ functions from Java

javac++google-app-enginejava-native-interface

提问by Costi Ciudatu

I am developing a Java application in which I need to call some C++ functions (from Google Talk library libjingle) . The objective is to run it all on Google App Engine (which only supports Python or Java).

我正在开发一个 Java 应用程序,我需要在其中调用一些 C++ 函数(来自 Google Talk 库 libjingle)。目标是在 Google App Engine(仅支持 Python 或 Java)上运行它。

How can I do this?

我怎样才能做到这一点?

回答by Costi Ciudatu

You need to define nativemethods in your java code for whatever you want to be implemented in C++ and directly access your native code. Then you run javahon your code and it will generate the C header files for you and you'll need to provide C++ implementations.

您需要native在 Java 代码中为要在 C++ 中实现的任何内容定义方法,并直接访问您的本机代码。然后你运行javah你的代码,它会为你生成 C 头文件,你需要提供 C++ 实现。

The native methods you can call from your Java code like any other methods and still they'll have their implementation written in C++ and talking to whatever other native library directly.

您可以像任何其他方法一样从 Java 代码调用本机方法,但它们的实现仍然是用 C++ 编写的,并直接与任何其他本机库对话。

You then need to set the java.library.path system property to include the shared C/C++ libraries that you require: the google library and your own JNI implementation library would be required in this case.

然后,您需要设置 java.library.path 系统属性以包含您需要的共享 C/C++ 库:在这种情况下需要 google 库和您自己的 JNI 实现库。

回答by André Caron

If the library has C bindings through a DLL/SO, I usually prefer writing wrappers in Java using Java Native Access (JNA)rather than writing the bindings in C/C++ using the Java Native Interface (JNI). The former is easier to manipulate as the JNI access to Java objects is a real pain in the neck. However, it's not as obvious to wrap C++ classes using that API.

如果库通过 DLL/SO 具有 C 绑定,我通常更喜欢使用Java Native Access (JNA)在 Java 中编写包装器,而不是使用Java Native Interface (JNI)在 C/C++ 中编写绑定。前者更容易操作,因为 JNI 访问 Java 对象是一个真正的痛点。但是,使用该 API 包装 C++ 类并不那么明显。

You might also want to look into the Simplified Wrapper and Interface Generator (SWIG)for automating part of this process!

您可能还想查看简化的包装器和接口生成器 (SWIG)以自动化此过程的一部分!

回答by Nick Johnson

You can't run native code on App Engine - only JRE code. If there's no avoiding the native code, you'll need to run this part of your app on another system, and call it from your App Engine app - or use the built-in XMPP API, in this case.

您不能在 App Engine 上运行本机代码 - 只能运行 JRE 代码。如果无法避免使用本机代码,则您需要在另一个系统上运行应用程序的这一部分,并从您的 App Engine 应用程序调用它 - 或者在这种情况下使用内置XMPP API