Netbeans ide ��� linux

Apache NetBeans 12.5

This tutorial needs a review. You can open a JIRA issue, or edit it in GitHub following these contribution guidelines.

March 2014 [Revision number: V8.0-1]

This tutorial takes you through the creation of a simple application that uses Java TM Native Interface (JNI) code written in the C programming language.

The tutorial is specific to Linux.

Requirements

To follow this tutorial, you need the following software and resources.

Java Developer Kit (JDK)

C and C++ compilers, make , gdb

See the NetBeans IDE 8.0 Installation Instructions and + Configuring the NetBeans IDE for C/C+/Fortran for information on downloading and installing the required software.

Setting Up Your Environment for the Tutorial

You need both Java modules and C/C modules for this tutorial. If you already have downloaded the NetBeans IDE C/C bundle, you can download the additional Java modules separately.

To determine if you have the Java and C/C modules, select File > New Project. The project categories should include both Java and C/C.

To download Java and C/C++ modules that may be missing:

In the NetBeans IDE, select Tools > Plugins.

In the Available Plugins tab, select the checkbox for Java or C/C++, depending on which is missing from your IDE. If you already have the plugins, they will be listed in the Installed tab.

Click Next in the NetBeans IDE Installer dialog box, accept the license terms checkbox, and click Install.

Click Finish when the installation is complete.

Setting Up the Java Application Project

This program requires a Java project and a C project. In this section, you will create and configure the Java project for the JNI application you will be developing. You will create a new Java application project, initialize its main class, and add a native method to this class.

Choose File > New Project. Select the Java category and Java Application project type. Click Next.

In the Project Name field, type JNIDemoJava .

You can change the Project Location to any directory on your computer, but here we use the default NetBeansProjects in the user directory.

Leave the Create Main Class checkbox selected and change the Main class name to jnidemojava.Main .

The IDE creates the NetBeansProjects/JNIDemoJava project folder.

Editing the Main Class Source

To open the Main class source in the editor, right-click the Main.java class node and choose Open.

Replace the line //TODO code application logic here in the main method with the following:

Notice the indicator in the left margin showing an error and lightbulb. Click on the indicator, and you are prompted with a shortcut to create the method nativePrint .

Click on this shortcut and the IDE inserts the following code:

Delete the line

Modify the nativePrint() method by inserting the native keyword into the method signature so that it now looks as follows:

The native keyword indicates that the method has an implementation located in an external native library. However, at runtime the library location is not clear.

The new main method should look as follows:

Right-click the project name and select Clean and Build. The project should build successfully.

Creating the Native Library Header File

In this section we use javah , a Java tool that creates a C header from a Java class.

In a terminal window, navigate to the NetBeansProjects directory.

Type the following:

A JNIDemoJava.h C header file is generated in the NetBeansProjects directory. This file is required to provide a correct function declaration for the native implementation of the nativePrint() method. You will need it later when you create the C part of this application.

Switch back to the NetBeans IDE window.

Summary

In this exercise you created a new Java application project, specified its location, and defined the package and name of the main class of the project. You also added a new method to the main class and marked it as a method having a native implementation. As a final step, you created a C header file, which is required later for the native library compilation.

Setting Up a New C/C++ Dynamic Library Project

This section shows you how to create the native part of the application. You will create the C++ Dynamic Library project and configure it to be able to build JNI code.

After you have set up the project, you will create the implementation for the native method you declared earlier in the Java part of the application.

Choose File > New Project. Under Categories, select C/C. Under Projects, select C/C Dynamic Library. Click Next.

In the Project Name field, type JNIDemoCdl .

In the Project Location field, use the same location that you used for the Java application project, NetBeansProjects . The location should be shown as the default value.

Accept the defaults for all other fields and click Finish.

The IDE creates the NetBeansProjects/JNIDemoCdl project folder.

Setting Project Properties

Right-click the JNIDemoCdl project node and choose Properties.

In the Properties dialog box, select the C Compiler node under the Build properties.

Click the Include Directories and Headers …​ button and click Add in the Include Directories and Headers dialog box.

Browse into your JDK directory, and select the include subdirectory.

Select the Store path as Absolute option, then click Select to add this directory to the project’s Include Directories.

Add the JDK’s include/linux directory in the same way, then click OK.

These settings are required to enable references to the Java jni.h library from your C code.

Find the Compilation Line area of the C Compiler options. Click in the text field of the Additional Options property and type -shared -m32 .

The -shared option tells the compiler to generate a dynamic library. The -m32 option tells the compiler to create a 32-bit binary. By default on 64-bit systems the compiled binaries are 64-bit, which causes a lot of problems with 32-bit JDKs.

Click the Linker category in the left panel.

Click the Output text field, and replace the string

with the string

to simplify the path of the resulting shared object file. This will make the file easer to reference from Java.

Click OK. The defined settings are saved.

Adding a Header File

Go to a terminal window and move the JNIDemoJava.h header file that you generated previously from your NetBeansProjects directory to the C/C++ Library project directory, NetBeansProjects/JNIDemoCdl . 2. In the Projects window, right-click the Header Files node of the JNIDemoCdl project and choose Add Existing Item. Navigate to the NetBeansProjects/JNIDemoCdl directory and select the JNIDemoJava.h file, then click Select.

The JNIDemoJava.h file appears under Header Files.

Implementing a Method

Right-click the Source Files node of the JNIDemoCdl project and choose New > C Source File. Type JNIDemo in the File Name field, and click Finish. The editor opens the JNIDemo.c file.

Edit the JNIDemo.c file by typing the following code:

Save the JNIDemo.c file.

Right-click the JNIDemoCdl project node and choose Build. The Output window displays BUILD SUCCESSFUL (total time 171ms) or similar.

Summary

In this exercise you created a new C/C++ Dynamic Library, specified its location, and configured it to be able to build a JNI implementation of your Java method. You added the generated header file for the native method you declared in the Java application, and implemented it.

Building and Running the Application

In this exercise, you will perform some final alterations to the Java part of the application. These changes are required to ensure the Java part properly loads the native library you compiled in the previous exercise. After that you will compile and run the resulting application.

Configuring the Java Project

Open the Main.java file in the editor.

Add the following initialization code for the C++ dynamic library after the public class Main line, using the path to the output file that you shortened in the previous exercise:

Replace full-path-to-NetBeansProjects-dir with the path to your NetBeansProjects directory, which should be something similar to /home/username/NetBeansProjects

Save the Main.java file.

Running the JNIDemoJava Application

Select the JNIDemoJava application in the Projects window.

Press F6 or click the Run button in the toolbar to run the application. The program should execute correctly and the Output window should display output similar to the following:

Summary

In this exercise you made some final configuration steps and ran the application to verify that the implementation of the native method comes from the native C library.

Next Steps

If you want to check your work against a working example, you can + download a zip file containing the source code+ from netbeans.org.

You can use the following documents to get more information:

Источник

Apache NetBeans 12.5

Software or Resource Version Required
This tutorial needs a review. You can open a JIRA issue, or edit it in GitHub following these contribution guidelines.

Март 2014 г. [Номер версии: V8.0-1]

В этой учебной программе рассматривается создание простого приложения, использующего код Java TM Native Interface (JNI), написанный на языке программирования C.

Этот учебный курс создан для Linux.

Требования

Для работы с этим учебным курсом требуется следующее программное обеспечение и ресурсы.

Комплект для разработчика на языке Java (JDK)

Компиляторы C и C++, make , gdb

Дополнительные сведения о загрузке и установки необходимого программного обеспечения см. в разделах Инструкции по установки IDE NetBeans 8.0 и + Настройка IDE NetBeans дляC/C+/Fortran.

Настройка среды для учебного курса

Для этого учебного курса потребуются модули Java и C/C. Если комплект C/C IDE NetBeans уже загружен, пользователи могут загрузить дополнительные модули Java по отдельности.

Чтобы определить наличие модулей Java и C/C, выберите пункт меню «Файл > Новый проект». В категории проектов должны входить Java и C/C.

Чтобы загрузить отсутствующие модули Java и C/C++, выполните следующие действия.

В IDE NetBeans выберите ‘Сервис’ > ‘Подключаемые модули’.

Во вкладке «Доступные подключаемые модули» установите флажок для Java или C/C++ в зависимости от того, какой модуль отсутствует в среде IDE. Если оба модуля уже установлены, они отобразятся во вкладке «Установлено».

Нажмите кнопку «Установить».

Щелкните ‘Далее’ в диалоговом окне установщика IDE NetBeans, установите флажок принятия условий лицензии установщика и щелкните ‘Установить’.

По завершении установки нажмите кнопку «Готово».

Настройка проекта приложения Java

Для данной программы требуются проект Java и проект C. В этом разделе описаны создание и настройка проекта Java для разрабатываемого приложения JNI. Для этого потребуется создать проект приложения Java, инициализировать его главный класс и добавить метод в машинном коде к этому классу.

Выберите команду «Файл» > «Новый проект». Выберите категорию «Java» и тип проекта «Приложение Java». Нажмите ‘Далее’.

В поле «Имя проекта» введите JNIDemoJava .

В качестве местоположения проекта можно указать любой каталог на компьютере. В этом примере используется папка по умолчанию «NetBeansProjects» в каталоге пользователя.

Не снимая флажок ‘Создать основной класс’, измените имя основного класса на jnidemojava.Main .

В среде IDE будет создана папка проекта NetBeansProjects/JNIDemoJava .

Изменение исходного кода главного класса

Чтобы открыть источник класса Main в редакторе, щелкните правой кнопкой мыши узел класса Main.java и выберите ‘Открыть’.

Замените строку //TODO code application logic here в методе main следующим кодом:

В поле слева появится индикатор в виде лампочки, сообщающий об ошибке. Щелкните индикатор. Отобразится ярлык для создания метода nativePrint .

Щелкните этот ярлык, после чего будет вставлен следующий код:

Измените метод nativePrint() : вставьте ключевое слово native в подпись метода, чтобы она выглядела следующим образом:

Ключевое слово native означает, что реализация этого метода размещена во внешней библиотеке в машинном коде. Однако при запуске местоположение библиотеки не ясно.

Новый метод main будет выглядеть следующим образом:

Правой кнопкой мыши щелкните имя проекта и выберите пункт «Очистить и собрать». После этого проект должен успешно собраться.

Создание файла заголовка библиотеки в машинном коде

В этом разделе будет использоваться javah – средство Java, используемое для создания заголовка на языке C из класса Java.

В окне терминала перейдите к каталогу NetBeansProjects .

Введите следующее значение:

В каталоге NetBeansProjects будет создан файл заголовка на языке C JNIDemoJava.h . Этот файл требуется для того, чтобы обеспечить предоставление правильного объявления функции для реализации метода nativePrint() в машинном коде. Он понадобится позже при создании части приложения на языке C.

Переключение обратно в окно IDE NetBeans.

Заключение

В этом упражнении вы создали новый проект приложения Java, указали его местоположение и определили пакет и имя главного класса этого проекта. Вы также добавили новый метод к главному классу и пометили его как метод с реализацией в машинном коде. В завершение вы создали файл заголовка на языке C, который понадобится позже при компиляции библиотеки в машинный код.

Настройка нового проекта динамической библиотеки на языке C/C++

В этом разделе рассматривается процесс создания части приложения в машинном коде. Вы создадите проект динамической библиотеки на языке C++ и настроите его для сборки кода JNI.

После настройки проекта вы создадите реализацию для метода в машинном коде, который был объявлен ранее в части приложения на языке Java.

Выберите команду «Файл» > «Новый проект». В окне «Категории» выберите C/C. В окне «Проекты» выберите «Динамическая библиотека C/C». Нажмите кнопку «Далее».

В поле «Имя проекта» введите JNIDemoCdl .

В поле «Местоположение проекта» укажите то же местоположение, которое было использовано для проекта приложения Java – NetBeansProjects . Это местоположение должно отобразиться по умолчанию.

Оставьте данные во всех остальных полях без изменения и нажмите ‘Готово’.

В среде IDE будет создана папка проекта NetBeansProjects/JNIDemoCdl .

Настройка свойств проекта

Правой кнопкой мыши щелкните узел проекта «JNIDemoCdl» и выберите «Свойства».

В диалоговом окне свойств выберите узел «Компилятор C» в свойствах «Сборка» узла.

Нажмите кнопку ‘Включить каталоги и заголовки…​’. В открывшемся диалоговом окне ‘Включение каталогов и заголовков’ нажмите ‘Добавить’.

Перейдите к каталогу JDK и выберите подкаталог include .

Выберите параметр ‘Сохранить путь как абсолютный’, затем нажмите кнопку ‘Выбрать’, чтобы добавить этот каталог во включенные каталоги проекта.

Аналогичным образом добавьте каталог JDK include/linux , затем нажмите кнопку «ОК».

Эти параметры требуются для включения ссылок на библиотеку Java jni.h из кода C.

Найдите область ‘Строка компиляции’ в параметрах компилятора C. Щелкните текстовое поле в свойстве ‘Дополнительные параметры’ и введите -shared -m32 .

Параметр -shared указывает создание динамической библиотеки. Параметр -m32 указывает создание двоичного файла для 32-разрядных платформ. По умолчанию в 64-разрядных системах компилируются двоичные файлы для 64-разрядных платформ, что приводит к возникновению множества проблем в 32-разрядных JDK.

Перейдите в категорию «Компоновщик» на левой панели.

Поставьте курсор в текстовое поле «Вывод» и замените строку

Источник

Читайте также:  Linux namespace что это
Оцените статью
Программное обеспечение или материал Требуемая версия