简体   繁体   English

如何使用Java实现C ++代码

[英]how to use java to implement C++ code

That is a phone interview question. 那是电话面试的问题。

Assume you have a C++ code, you want to implement the code by using Java rather than rewriting the code. 假设您有C ++代码,则想通过使用Java而不是重写代码来实现代码。 How would you solve that? 您将如何解决?

I cannot figure out this question. 我无法弄清楚这个问题。 Can anyone told me the solution?(is it possible by import some package or java library?) 有人可以告诉我解决方案吗?(可以通过导入一些包或java库吗?)

Thanks 谢谢

Using Java Native Interface (JNI), you can use a method written in c++(or some other language) in your java code 使用Java本机接口(JNI),您可以在Java代码中使用以c ++(或其他某种语言)编写的方法

  1. Begin by writing the Java program. 首先编写Java程序。 Create a Java class that declares the native method; 创建一个声明本机方法的Java类; this class contains the declaration or signature for the native method. 此类包含本机方法的声明或签名。 It also includes a main method which calls the native method. 它还包括一个主要方法,该方法调用了本机方法。
  2. Compile the Java class that declares the native method and the main method. 编译声明本机方法和main方法的Java类。
  3. Generate a header file for the native method using javah with the native interface flag -jni. 使用带有本机接口标志-jni的javah为本机方法生成头文件。 Once you've generated the header file you have the formal signature for your native method. 生成头文件后,便具有本机方法的正式签名。
  4. Write the implementation of the native method in the programming language of your choice, such as C or C++. 用您选择的编程语言(例如C或C ++)编写本机方法的实现。 (this is what you are already given in this case). (在这种情况下,这就是您所得到的)。
  5. Compile the header and implementation files into a shared library file. 将头文件和实现文件编译为共享库文件。
  6. Run the Java program. 运行Java程序。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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