### Installing the Application Executable Source: https://github.com/dart-lang/native/blob/main/pkgs/jnigen/example/pdfbox_plugin/example/linux/CMakeLists.txt Installs the application executable to the root of the installation prefix for the Runtime component. ```cmake install(TARGETS ${BINARY_NAME} RUNTIME DESTINATION "${CMAKE_INSTALL_PREFIX}" COMPONENT Runtime) ``` -------------------------------- ### Install Application Bundle Source: https://github.com/dart-lang/native/blob/main/pkgs/jni/example/linux/CMakeLists.txt Configures the installation process to create a relocatable application bundle. It cleans the bundle directory, installs the executable, data files, libraries, and assets. ```cmake install(CODE " file(REMOVE_RECURSE \"${BUILD_BUNDLE_DIR}/\") " COMPONENT Runtime) ``` ```cmake install(TARGETS ${BINARY_NAME} RUNTIME DESTINATION "${CMAKE_INSTALL_PREFIX}" COMPONENT Runtime) ``` ```cmake install(FILES "${FLUTTER_ICU_DATA_FILE}" DESTINATION "${INSTALL_BUNDLE_DATA_DIR}" COMPONENT Runtime) ``` ```cmake install(FILES "${FLUTTER_LIBRARY}" DESTINATION "${INSTALL_BUNDLE_LIB_DIR}" COMPONENT Runtime) ``` ```cmake foreach(bundled_library ${PLUGIN_BUNDLED_LIBRARIES}) install(FILES "${bundled_library}" DESTINATION "${INSTALL_BUNDLE_LIB_DIR}" COMPONENT Runtime) endforeach(bundled_library) ``` ```cmake install(CODE " file(REMOVE_RECURSE \"${INSTALL_BUNDLE_DATA_DIR}/${FLUTTER_ASSET_DIR_NAME}\") " COMPONENT Runtime) ``` ```cmake install(DIRECTORY "${PROJECT_BUILD_DIR}/${FLUTTER_ASSET_DIR_NAME}" DESTINATION "${INSTALL_BUNDLE_DATA_DIR}" COMPONENT Runtime) ``` -------------------------------- ### Run SwiftGen Example Source: https://github.com/dart-lang/native/blob/main/pkgs/swiftgen/example/README.md Execute the example application with a specified audio file. Replace with the path to your audio file. ```shell dart play_audio.dart ``` -------------------------------- ### CMake Minimum Version and Project Setup Source: https://github.com/dart-lang/native/blob/main/pkgs/jnigen/android_test_runner/android/app/CMakeLists.txt Specifies the minimum required CMake version and defines the project name, version, and primary language. This is a standard starting point for CMake projects. ```cmake cmake_minimum_required(VERSION 3.10) project(simple_package VERSION 0.0.1 LANGUAGES C) ``` -------------------------------- ### Installing Bundled Plugin Libraries Source: https://github.com/dart-lang/native/blob/main/pkgs/jnigen/example/pdfbox_plugin/example/linux/CMakeLists.txt Iterates through a list of bundled plugin libraries and installs each to the library directory of the installation bundle. ```cmake foreach(bundled_library ${PLUGIN_BUNDLED_LIBRARIES}) install(FILES "${bundled_library}" DESTINATION "${INSTALL_BUNDLE_LIB_DIR}" COMPONENT Runtime) endforeach(bundled_library) ``` -------------------------------- ### Installing Flutter Library Source: https://github.com/dart-lang/native/blob/main/pkgs/jnigen/example/pdfbox_plugin/example/linux/CMakeLists.txt Installs the main Flutter library file to the library directory of the installation bundle. ```cmake install(FILES "${FLUTTER_LIBRARY}" DESTINATION "${INSTALL_BUNDLE_LIB_DIR}" COMPONENT Runtime) ``` -------------------------------- ### Generate Bindings Source: https://github.com/dart-lang/native/blob/main/pkgs/ffigen/example/shared_bindings/README.md Run this command at the root of the example directory to generate the necessary bindings. ```bash dart run generate.dart ``` -------------------------------- ### Setting Installation Directories Source: https://github.com/dart-lang/native/blob/main/pkgs/jnigen/example/pdfbox_plugin/example/linux/CMakeLists.txt Defines the destination directories for data and libraries within the installation bundle. ```cmake set(INSTALL_BUNDLE_DATA_DIR "${CMAKE_INSTALL_PREFIX}/data") set(INSTALL_BUNDLE_LIB_DIR "${CMAKE_INSTALL_PREFIX}/lib") ``` -------------------------------- ### Run the Dart Example Source: https://github.com/dart-lang/native/blob/main/pkgs/ffigen/example/swift/README.md Execute the generated Dart example code that utilizes the FFIgen bindings to interact with the Swift library. ```shell dart run example.dart ``` -------------------------------- ### Install LLVM on Windows using winget Source: https://github.com/dart-lang/native/blob/main/pkgs/ffigen/README.md Install LLVM on Windows using the winget package manager. ```bash winget install -e --id LLVM.LLVM ``` -------------------------------- ### Setup Native Libraries Source: https://github.com/dart-lang/native/blob/main/pkgs/jnigen/example/pdfbox_plugin/dart_example/README.md Run this command to set up the native libraries required for the PDFBox plugin. ```bash dart run jni:setup ``` -------------------------------- ### jnigen One-Time Setup Source: https://github.com/dart-lang/native/blob/main/pkgs/jnigen/test/README.md Run this command once to set up the jnigen environment before running tests. ```bash dart run jnigen:setup ``` -------------------------------- ### Run the cJson Example Source: https://github.com/dart-lang/native/blob/main/pkgs/ffigen/example/c_json/README.md Execute the Dart main file to run the example that uses the generated cJson bindings. ```bash dart main.dart ``` -------------------------------- ### Run Flutter Application Source: https://github.com/dart-lang/native/blob/main/pkgs/jnigen/example/pdfbox_plugin/example/README.md After generating bindings, navigate to the example directory and run the Flutter application. The --release flag is recommended for performance. ```bash cd example/ flutter run --release ``` -------------------------------- ### Install clang-devel on Fedora/CentOS Source: https://github.com/dart-lang/native/blob/main/pkgs/ffigen/README.md Use dnf to install the clang-devel package on Fedora-based systems. ```bash sudo dnf install clang-devel ``` -------------------------------- ### CMake Minimum Version and Project Setup Source: https://github.com/dart-lang/native/blob/main/pkgs/jnigen/example/pdfbox_plugin/windows/CMakeLists.txt Sets the minimum required CMake version for the project and defines the project name and languages. Ensure Visual Studio with CMake 3.14 or later is installed. ```cmake cmake_minimum_required(VERSION 3.14) # Project-level configuration. set(PROJECT_NAME "pdfbox_plugin") project(${PROJECT_NAME} LANGUAGES CXX) ``` -------------------------------- ### Install Flutter Assets Source: https://github.com/dart-lang/native/blob/main/pkgs/jnigen/example/pdfbox_plugin/example/linux/CMakeLists.txt Installs Flutter assets by removing any existing directory and then copying the new assets. This ensures a clean installation of assets. ```cmake set(FLUTTER_ASSET_DIR_NAME "flutter_assets") install(CODE " file(REMOVE_RECURSE \"${INSTALL_BUNDLE_DATA_DIR}/${FLUTTER_ASSET_DIR_NAME}\") " COMPONENT Runtime) install(DIRECTORY "${PROJECT_BUILD_DIR}/${FLUTTER_ASSET_DIR_NAME}" DESTINATION "${INSTALL_BUNDLE_DATA_DIR}" COMPONENT Runtime) ``` -------------------------------- ### Install libclang-dev on Debian/Ubuntu Source: https://github.com/dart-lang/native/blob/main/pkgs/ffigen/README.md Use apt-get to install the libclang-dev package on Debian-based systems. ```bash sudo apt-get install libclang-dev ``` -------------------------------- ### Pass Compiler Options via Command Line Source: https://github.com/dart-lang/native/blob/main/pkgs/ffigen/README.md Example of passing compiler options directly through the command line interface for FFIgen. ```bash dart run ffigen --compiler-opts "-I/headers -L 'path/to/folder name/file'" ``` -------------------------------- ### Generate Native Bindings with ffigen Source: https://github.com/dart-lang/native/blob/main/pkgs/ffigen/example/ffinative/README.md Run this command at the root of the example directory to generate Dart bindings from a C header file using a configuration file. ```bash dart run ffigen --config config.yaml ``` -------------------------------- ### Installation Prefix Configuration Source: https://github.com/dart-lang/native/blob/main/pkgs/jnigen/example/pdfbox_plugin/example/linux/CMakeLists.txt Configures the installation prefix to a bundle directory within the build directory, especially when the default prefix is used. ```cmake set(BUILD_BUNDLE_DIR "${PROJECT_BINARY_DIR}/bundle") if(CMAKE_INSTALL_PREFIX_INITIALIZED_TO_DEFAULT) set(CMAKE_INSTALL_PREFIX "${BUILD_BUNDLE_DIR}" CACHE PATH "..." FORCE) endif() ``` -------------------------------- ### YAML Configuration Example Source: https://github.com/dart-lang/native/blob/main/pkgs/hooks/CONTRIBUTING.md A simple YAML configuration snippet. This is often used in conjunction with data assets or build configurations. ```yaml foo: bar ``` -------------------------------- ### Install Xcode Command Line Tools on macOS Source: https://github.com/dart-lang/native/blob/main/pkgs/ffigen/README.md Install the Xcode command line tools on macOS using the xcode-select command. ```bash xcode-select --install ``` -------------------------------- ### Generated CSS Example Source: https://github.com/dart-lang/native/blob/main/pkgs/record_use/doc/use_cases/jaspr.md Example of CSS rules generated based on recorded component usage and styles. ```css .column-spacing-42 { padding: 42px; } .column-cross-axis-center { align-items: center; } ``` -------------------------------- ### Run JNIgen Command Source: https://github.com/dart-lang/native/blob/main/pkgs/jnigen/example/kotlin_plugin/README.md Execute this command from the kotlin_plugin project root to regenerate JNI bindings. Ensure the example app's dependencies are resolved beforehand. ```bash dart run jnigen --config jnigen.yaml # run from kotlin_plugin project root ``` -------------------------------- ### Clean Build Bundle Directory Source: https://github.com/dart-lang/native/blob/main/pkgs/jnigen/example/pdfbox_plugin/example/linux/CMakeLists.txt Installs a code that removes the build bundle directory before installation to ensure a clean state. ```cmake install(CODE " file(REMOVE_RECURSE \"${BUILD_BUNDLE_DIR}/\") " COMPONENT Runtime) ``` -------------------------------- ### Build C Library with Native Toolchain Source: https://github.com/dart-lang/native/blob/main/pkgs/code_assets/README.md This example demonstrates building a C library using `native_toolchain_c` within a build hook. It configures build defines, such as exporting symbols for Windows DLLs. ```dart import 'package:code_assets/code_assets.dart'; import 'package:hooks/hooks.dart'; import 'package:native_toolchain_c/native_toolchain_c.dart'; final builder = CBuilder.library( name: 'sqlite3', assetName: 'src/third_party/sqlite3.g.dart', sources: ['third_party/sqlite/sqlite3.c'], ); void main(List args) async { await build(args, (input, output) async { if (input.config.buildCodeAssets) { await builder.run( input: input, output: output, defines: { if (input.config.code.targetOS == OS.windows) // Ensure symbols are exported in dll. 'SQLITE_API': '__declspec(dllexport)', }, ); } }); } ``` -------------------------------- ### Spawn a JVM Source: https://github.com/dart-lang/native/blob/main/pkgs/jnigen/README.md Call `Jni.spawn` to start a JVM. It assumes dependencies are built into the same target directory for automatic loading. ```dart Jni.spawn() ``` -------------------------------- ### Spawn JVM with Custom Build Path Source: https://github.com/dart-lang/native/blob/main/pkgs/jnigen/README.md If a custom build path was used with `dart run jni:setup --build-path path/to/dylib`, pass the same path to `Jni.spawn`. ```dart Jni.spawn(dylibDir: 'path/to/dylib') ``` -------------------------------- ### Configure Flutter library and headers Source: https://github.com/dart-lang/native/blob/main/pkgs/jni/example/linux/flutter/CMakeLists.txt Sets the paths for the Flutter library and its header files. These are published to the parent scope for use in the installation step. ```cmake set(FLUTTER_LIBRARY "${EPHEMERAL_DIR}/libflutter_linux_gtk.so") # Published to parent scope for install step. set(FLUTTER_LIBRARY ${FLUTTER_LIBRARY} PARENT_SCOPE) set(FLUTTER_ICU_DATA_FILE "${EPHEMERAL_DIR}/icudtl.dat" PARENT_SCOPE) set(PROJECT_BUILD_DIR "${PROJECT_DIR}/build/" PARENT_SCOPE) set(AOT_LIBRARY "${PROJECT_DIR}/build/lib/libapp.so" PARENT_SCOPE) ``` -------------------------------- ### Project Configuration Source: https://github.com/dart-lang/native/blob/main/pkgs/jnigen/example/pdfbox_plugin/linux/CMakeLists.txt Configures the project name and specifies C++ as the primary language for the project. This is a standard CMake setup for C++ projects. ```cmake set(PROJECT_NAME "pdfbox_plugin") project(${PROJECT_NAME} LANGUAGES CXX) ``` -------------------------------- ### Example IconData Usage Source: https://github.com/dart-lang/native/blob/main/pkgs/record_use/doc/use_cases/icon_data.md Demonstrates how to declare static const instances of IconData, commonly used for defining a set of icons within a class. This pattern is essential for organizing and accessing icons. ```dart abstract final class GalleryIcons { static const IconData tooltip = IconData(0xe900, fontFamily: 'GalleryIcons'); static const IconData text_fields_alt = IconData(0xe901, fontFamily: 'GalleryIcons'); // ... ``` -------------------------------- ### Add Code and Data Assets in Dart Source: https://github.com/dart-lang/native/blob/main/pkgs/hooks/CONTRIBUTING.md Example of how to add code and data assets within a build process using the hooks library. Ensure the source file for code assets is correctly referenced. ```dart import 'package:code_assets/code_assets.dart'; import 'package:data_assets/data_assets.dart'; import 'package:hooks/hooks.dart'; void main(List arguments) async { await build(arguments, (input, output) async { output.assets.code.add( CodeAsset( name: 'my_code', file: Uri.file('path/to/file'), package: input.packageName, linkMode: DynamicLoadingBundled(), ), ); output.assets.data.add( DataAsset( name: 'my_data', file: Uri.file('path/to/file'), package: input.packageName, ), ); }); } ``` -------------------------------- ### Java Identifiers Starting with Underscore Source: https://github.com/dart-lang/native/blob/main/pkgs/jnigen/doc/java_differences.md To maintain public accessibility in Dart for Java identifiers that start with an underscore (which are private in Dart), JNIgen prepends them with a dollar sign. This example shows the conversion of a Java class and method starting with underscores. ```java // Java public class _Example { public void _printMessage() { System.out.println("Hello from Java!"); } } ``` -------------------------------- ### Installing Flutter ICU Data Source: https://github.com/dart-lang/native/blob/main/pkgs/jnigen/example/pdfbox_plugin/example/linux/CMakeLists.txt Installs the Flutter ICU data file to the data directory of the installation bundle. ```cmake install(FILES "${FLUTTER_ICU_DATA_FILE}" DESTINATION "${INSTALL_BUNDLE_DATA_DIR}" COMPONENT Runtime) ``` -------------------------------- ### Build Native Library (Treeshake using Instances) Source: https://github.com/dart-lang/native/blob/main/pkgs/record_use/test_data/drop_dylib_recording/README.md Builds the native library and tree-shakes unused libraries based on recorded instances. Only the 'add' library will be present in the `lib/` folder. ```bash dart --enable-experiment=record-use build bin/drop_dylib_recording_instances.dart ``` ```bash The `lib/` folder now contains only the `add` library. ``` ```bash ./bin/drop_dylib_recording_calls/drop_dylib_recording_instances.exe ``` ```bash Prints `Hello world: 7!` ``` -------------------------------- ### Run PDF Info Tool Source: https://github.com/dart-lang/native/blob/main/pkgs/jnigen/example/pdfbox_plugin/dart_example/README.md Execute the PDF info tool with the path to your PDF file. Ensure the `pdfbox_plugin` bindings have been generated in the parent directory. ```bash dart run bin/pdf_info.dart ``` -------------------------------- ### Build Native Library (Keep All) Source: https://github.com/dart-lang/native/blob/main/pkgs/record_use/test_data/drop_dylib_recording/README.md Builds the native library including all components without tree-shaking. The `lib/` folder will contain both the 'add' and 'multiply' libraries. ```bash dart --enable-experiment=record-use build bin/drop_dylib_recording_all.dart ``` ```bash The `lib/` folder now contains both libraries ``` ```bash ./bin/drop_dylib_recording_all/drop_dylib_recording_all.exe add ``` ```bash Prints `Hello world: 7!` ``` -------------------------------- ### Set Flutter Library and ICU Data for Install Source: https://github.com/dart-lang/native/blob/main/pkgs/jnigen/example/pdfbox_plugin/example/windows/flutter/CMakeLists.txt Exports the Flutter library path and ICU data file path to the parent scope for installation. ```cmake set(FLUTTER_LIBRARY ${FLUTTER_LIBRARY} PARENT_SCOPE) set(FLUTTER_ICU_DATA_FILE "${EPHEMERAL_DIR}/icudtl.dat" PARENT_SCOPE) ``` -------------------------------- ### Build Native Library (Treeshake using Calls) Source: https://github.com/dart-lang/native/blob/main/pkgs/record_use/test_data/drop_dylib_recording/README.md Builds the native library and tree-shakes unused libraries based on recorded calls. Only the 'add' library will be present in the `lib/` folder. ```bash dart --enable-experiment=record-use build bin/drop_dylib_recording_calls.dart ``` ```bash The `lib/` folder now contains only the `add` library. ``` ```bash ./bin/drop_dylib_recording_calls/drop_dylib_recording_calls.exe ``` ```bash Prints `Hello world: 7!` ``` -------------------------------- ### Install AOT Library Conditionally Source: https://github.com/dart-lang/native/blob/main/pkgs/jni/example/linux/CMakeLists.txt Installs the AOT library to the runtime destination only when the build type is not Debug. This ensures that debug symbols or development-specific libraries are not included in release builds. ```cmake if(NOT CMAKE_BUILD_TYPE MATCHES "Debug") install(FILES "${AOT_LIBRARY}" DESTINATION "${INSTALL_BUNDLE_LIB_DIR}" COMPONENT Runtime) endif() ``` -------------------------------- ### Initialize JVM on desktop with Jni.spawn Source: https://context7.com/dart-lang/native/llms.txt Initialize a JVM instance on non-Android platforms using Jni.spawn. Call this once at program startup before using any JNI classes. It requires specifying the directory for JNI libraries, the classpath, and optional JVM options. ```dart import 'package:jni/jni.dart'; void main() { // Desktop only — spawn a JVM with classpath Jni.spawn( dylibDir: 'build/jni_libs', classPath: ['build/libs/myapp.jar', 'build/libs/dependency.jar'], jvmOptions: ['-Xmx512m', '-Xms64m'], ); // Look up a Java class final javaClass = JClass.forName('java/lang/System'); final versionField = javaClass.staticFieldId('out', 'Ljava/io/PrintStream;'); print('JNI initialized successfully'); // Use generated bindings from package:jnigen // final list = JList.of([1.toJInteger(), 2.toJInteger()]); // list.forEach((e) => print(e.intValue())); // list.release(); } ``` -------------------------------- ### Using $XCODE Variable Substitution in FFIgen Source: https://github.com/dart-lang/native/blob/main/pkgs/ffigen/doc/apple_apis.md Use the `$XCODE` variable substitution in your FFIgen configuration to dynamically reference the Xcode installation directory. This ensures your header file paths are correct across different Xcode versions and installations. ```yaml headers: entry-points: - '$MACOS_SDK/System/Library/Frameworks/Foundation.framework/Headers/NSDate.h' ``` -------------------------------- ### Build Dynamic Libraries for FFIgen Tests Source: https://github.com/dart-lang/native/blob/main/pkgs/ffigen/test/README.md Execute this command to build the dynamic libraries required by some FFIgen tests. This is a prerequisite for running the test suite. ```shell dart run test/setup.dart ``` -------------------------------- ### Translate Message Calls Source: https://github.com/dart-lang/native/blob/main/pkgs/record_use/doc/use_cases/messages.md Example calls to translate methods, demonstrating how messages are looked up or evaluated with specific IDs and application IDs. ```dart String translateFoo() => lookup(/*int id of foo*/0, 'baz'); String translateBar(String name) => evaluate(/*int id of foo*/0, 'baz', name); ``` -------------------------------- ### Run FFIgen Tests Source: https://github.com/dart-lang/native/blob/main/pkgs/ffigen/test/README.md Execute this command to run the FFIgen test suite. Ensure dynamic libraries are built beforehand. ```shell dart test ``` -------------------------------- ### Export Build Variables to Parent Scope Source: https://github.com/dart-lang/native/blob/main/pkgs/jnigen/example/pdfbox_plugin/example/linux/flutter/CMakeLists.txt Exports key build variables to the parent scope, making them available for installation or other build steps. ```cmake # Published to parent scope for install step. set(FLUTTER_LIBRARY ${FLUTTER_LIBRARY} PARENT_SCOPE) set(FLUTTER_ICU_DATA_FILE "${EPHEMERAL_DIR}/icudtl.dat" PARENT_SCOPE) set(PROJECT_BUILD_DIR "${PROJECT_DIR}/build/" PARENT_SCOPE) set(AOT_LIBRARY "${PROJECT_DIR}/build/lib/libapp.so" PARENT_SCOPE) ``` -------------------------------- ### Interface with System Libraries Source: https://github.com/dart-lang/native/blob/main/pkgs/code_assets/README.md This snippet shows how to interface with system libraries by adding `CodeAsset` entries with different `linkMode` configurations based on the target operating system. ```dart import 'package:code_assets/code_assets.dart'; import 'package:hooks/hooks.dart'; void main(List args) async { await build(args, (input, output) async { if (input.config.buildCodeAssets) { switch (input.config.code.targetOS) { case OS.android || OS.iOS || OS.linux || OS.macOS: output.assets.code.add( CodeAsset( package: 'host_name', name: 'src/third_party/unix.dart', linkMode: LookupInProcess(), ), ); case OS.windows: output.assets.code.add( CodeAsset( package: 'host_name', name: 'src/third_party/windows.dart', linkMode: DynamicLoadingSystem(Uri.file('ws2_32.dll')), ), ); case final os: throw UnsupportedError('Unsupported OS: ${os.name}.'); } } }); } ``` -------------------------------- ### Generate PDFBox Bindings Source: https://github.com/dart-lang/native/blob/main/pkgs/jnigen/example/pdfbox_plugin/example/README.md Use this command to download PDFBox JARs and generate Dart and C bindings for the plugin. Ensure you are in the correct directory. ```bash dart run jnigen --config jnigen.yaml ``` -------------------------------- ### Project Name and Subdirectory Inclusion Source: https://github.com/dart-lang/native/blob/main/pkgs/jni/windows/CMakeLists.txt Defines the project name and includes the source directory for shared components. This setup is crucial for organizing the project structure. ```cmake set(PROJECT_NAME "jni") project(${PROJECT_NAME} LANGUAGES CXX) add_subdirectory("${CMAKE_CURRENT_SOURCE_DIR}/../src" "${CMAKE_CURRENT_BINARY_DIR}/shared") ``` -------------------------------- ### Enable EXPERIMENTAL FFI Native Bindings Source: https://github.com/dart-lang/native/blob/main/pkgs/ffigen/README.md Use 'ffi-native' to generate '@Native' bindings instead of using 'DynamicLibrary' or 'lookup'. This feature is experimental. ```yaml ffi-native: asset-id: 'package:some_pkg/asset' # Optional, was assetId in previous versions ``` -------------------------------- ### Configure Headers for FFIgen YAML Source: https://github.com/dart-lang/native/blob/main/pkgs/ffigen/README.md Define entry points and include directives for header files. Glob syntax is supported for matching multiple files. ```yaml headers: entry-points: - 'folder/**.h' - 'folder/specific_header.h' include-directives: - '**index.h' - '**/clang-c/**' - '/full/path/to/a/header.h' ``` -------------------------------- ### Dart PDDocument Class Definition Source: https://github.com/dart-lang/native/blob/main/pkgs/record_use/doc/use_cases/jnigen.md Example of a Dart class generated by JNIgen, extending JObject and including factory constructors. This is used to track possible class instantiations. ```dart class PDDocument extends jni$_.JObject { PDDocument.fromReference( jni$_.JReference reference, ); factory PDDocument() { return PDDocument.fromReference( _new$(_class.reference.pointer, _id_new$ as jni$_.JMethodIDPtr) .reference); } factory PDDocument.new$1( jni$_.JObject? memUsageSetting, ); } ``` -------------------------------- ### Configure Preamble in FFIgen Source: https://github.com/dart-lang/native/blob/main/pkgs/ffigen/README.md Use the 'preamble' option to specify raw header content that will be pasted directly into the generated file. ```yaml preamble: | // ignore_for_file: camel_case_types, non_constant_identifier_names ``` -------------------------------- ### Generate JNI Bindings with Maven Dependencies Source: https://github.com/dart-lang/native/blob/main/pkgs/jnigen/example/maven_libs/README.md Run this command to regenerate JNI bindings when working with Maven dependencies. Ensure your example app's dependencies are resolved first. ```bash dart run tool/generate_bindings.dart ``` -------------------------------- ### System Dependencies and Application ID Definition Source: https://github.com/dart-lang/native/blob/main/pkgs/jnigen/example/pdfbox_plugin/example/linux/CMakeLists.txt Finds PkgConfig and GTK, and defines the APPLICATION_ID as a preprocessor macro. ```cmake find_package(PkgConfig REQUIRED) pkg_check_modules(GTK REQUIRED IMPORTED_TARGET gtk+-3.0) add_definitions(-DAPPLICATION_ID="${APPLICATION_ID}") ``` -------------------------------- ### Add jvm.dll to PATH on Windows (PowerShell) Source: https://github.com/dart-lang/native/blob/main/pkgs/jnigen/README.md Append the path of `jvm.dll` in your JDK installation to the PATH environment variable for the current PowerShell session. For permanent changes, use Control Panel. ```powershell $env:Path += ";${env:JAVA_HOME}\bin\server" ``` -------------------------------- ### Specify Include Paths for Clang Source: https://github.com/dart-lang/native/blob/main/pkgs/ffigen/doc/errors.md Use `compiler-opts` in your configuration to provide include paths to Clang, resolving missing header errors. ```yaml compiler-opts: - "-I/path/to/folder" ``` -------------------------------- ### Import and Use Generated Bindings in Dart Source: https://github.com/dart-lang/native/blob/main/pkgs/ffigen/README.md Demonstrates how to import the generated FFIgen bindings file and call the native C function from Dart code. ```dart import 'add.g.dart'; // ... void answerToLife() { print('The answer to the Ultimate Question is ${add(40, 2)}!'); } ``` -------------------------------- ### Compile a C/C++ executable with CBuilder.executable Source: https://context7.com/dart-lang/native/llms.txt Build a standalone native executable from C/C++ sources. Specify sources, include paths, language, and preprocessor defines. ```dart // hook/build.dart — build a native tool executable import 'package:hooks/hooks.dart'; import 'package:native_toolchain_c/native_toolchain_c.dart'; void main(List args) async { await build(args, (input, output) async { await CBuilder.executable( name: 'codegen_tool', sources: ['tool/codegen.c'], includes: ['tool/include'], language: Language.c, defines: {'TOOL_VERSION': '"0.1"'}, ).run(input: input, output: output); }); } ``` -------------------------------- ### Translate Java to Dart with JNIgen and Gemini Source: https://github.com/dart-lang/native/blob/main/pkgs/native_doc_dartifier/README.md This Java snippet demonstrates image capture setup. The equivalent Dart code uses JNI bindings generated by JNIgen to achieve similar functionality. ```java public void onClick() { ImageCapture.OutputFileOptions outputFileOptions = new ImageCapture.OutputFileOptions.Builder(new File(...)).build(); imageCapture.takePicture(outputFileOptions, cameraExecutor, new ImageCapture.OnImageSavedCallback() { @Override public void onImageSaved(ImageCapture.OutputFileResults outputFileResults) { // insert your code here. } @Override public void onError(ImageCaptureException error) { // insert your code here. } } ); } ``` ```dart void onClick() { final ImageCapture$OutputFileOptions outputFileOptions = ImageCapture$OutputFileOptions$Builder(File("...".toJString())).build(); imageCapture.takePicture$1(outputFileOptions, cameraExecutor, ImageCapture$OnImageSavedCallback.implement( $ImageCapture$OnImageSavedCallback( onImageSaved: (ImageCapture$OutputFileResults outputFileResults) { // insert your code here. }, onError: (ImageCaptureException error) { // insert your code here. } ))); } ``` -------------------------------- ### Project Name and Language Source: https://github.com/dart-lang/native/blob/main/pkgs/jni/linux/CMakeLists.txt Sets the project name to 'jni' and specifies CXX as the programming language. ```cmake set(PROJECT_NAME "jni") project(${PROJECT_NAME} LANGUAGES CXX) ``` -------------------------------- ### Dart to Java Identifier Mapping Source: https://github.com/dart-lang/native/blob/main/pkgs/record_use/doc/use_cases/jnigen.md Example of a Dart map used to link Dart identifiers to their original Java/Kotlin unique names. This is crucial for JNIgen to correctly map calls and generate ProGuard rules. ```dart const dartToJava = { DartMethodIdentifer( importUrl: 'package:foo/foo.dart', name: 'Bar', methodName: 'baz', ) : JavaMethodDefinition( qualifiedImport: 'org.foo.foo', name: 'Bar', methodName: 'baz', ), // ... } ``` -------------------------------- ### Generate Objective C Bindings with FFIgen Source: https://github.com/dart-lang/native/blob/main/pkgs/ffigen/example/objective_c/README.md Run the Dart script to generate the FFIgen bindings for the Objective C library. This will create the `avf_audio_bindings.dart` file. ```bash dart run generate_code.dart ``` -------------------------------- ### Build Swift Library with Objective-C Header Source: https://github.com/dart-lang/native/blob/main/pkgs/ffigen/example/swift/README.md Use the `swiftc` tool to compile Swift code into a dynamic library and generate an Objective-C wrapper header. This header is necessary for FFIgen to interface with the Swift library. ```shell swiftc -c swift_api.swift \ -module-name swift_module \ -emit-objc-header-path third_party/swift_api.h \ -emit-library -o libswiftapi.dylib ``` -------------------------------- ### Implementing a Class to Avoid Overcapturing in Dart Source: https://github.com/dart-lang/native/blob/main/pkgs/jnigen/doc/lifecycle.md This example demonstrates how to implement a class to manage references and avoid accidental overcapturing within closures. This approach helps in preventing GC cycles by explicitly managing the lifecycle of references. ```dart final class BarImpl with $Bar { final WeakReference weakFoo; BarImpl(this.weakFoo); @override void f() { final foo = weakFoo.target; if (foo == null) { throw StateError(); } return foo; } } void main() { final weakFoo = WeakReference(foo); foo.bar = Bar.implement(BarImpl(weakFoo)); // ... } ``` -------------------------------- ### ApiSummarizer Command Line Usage Source: https://github.com/dart-lang/native/blob/main/pkgs/jnigen/java/README.md This shows the command-line interface for ApiSummarizer, including available options for specifying source directories, class paths, and backend preferences. ```bash usage: java -jar [-s ] [-c ] Class or package names should be fully qualified. -b,--backend backend to use for summary generation ('doclet' or 'asm'). -c,--classes paths to search for compiled classes -D,--doctool-args Arguments to pass to the documentation tool -M,--use-modules use Java modules -m,--module-names comma separated list of module names -r,--recursive Include dependencies of classes -s,--sources paths to search for source files -v,--verbose Enable verbose output ``` -------------------------------- ### Hook Error Handling in Dart Native Source: https://context7.com/dart-lang/native/llms.txt Handle build and infrastructure errors by throwing `BuildError` or `InfraError`. This ensures proper failure output and exit codes. The example checks for a required tool (`cmake`) and simulates a download failure. ```dart import 'package:hooks/hooks.dart'; import 'dart:io'; void main(List args) async { await build(args, (input, output) async { // Check for required tool final result = await Process.run('cmake', ['--version']); if (result.exitCode != 0) { throw BuildError( message: 'cmake not found. Install cmake to build this package.', ); } // Signal infrastructure failure (e.g., network issue) final downloadOk = await _downloadAsset(); if (!downloadOk) { throw InfraError( message: 'Failed to download prebuilt binary. Check network.', wrappedException: Exception('HTTP 503'), ); } }); } Future _downloadAsset() async => true; // placeholder ``` -------------------------------- ### Build Input/Output Types in Dart Native Hooks Source: https://context7.com/dart-lang/native/llms.txt Use `BuildInput` to access build configuration and `BuildOutputBuilder` to collect assets and dependencies. This example shows how to read build context, code configuration, and emit code and data assets. ```dart import 'package:code_assets/code_assets.dart'; import 'package:data_assets/data_assets.dart'; import 'package:hooks/hooks.dart'; void main(List args) async { await build(args, (BuildInput input, BuildOutputBuilder output) async { // Read build context print(input.packageName); // e.g. 'my_package' print(input.packageRoot); // file:///path/to/package/ print(input.outputDirectory); // unique dir for this config print(input.config.buildAssetTypes); // ['native_code', ...] print(input.config.linkingEnabled); // bool // Read code config (via code_assets extension) final codeConfig = input.config.code; print(codeConfig.targetOS); // OS.linux / OS.android / ... print(codeConfig.targetArchitecture);// Architecture.arm64 / ... print(codeConfig.linkModePreference);// LinkModePreference.dynamic // Emit a code asset (pre-built dylib) output.assets.code.add( CodeAsset( package: input.packageName, name: 'mylib.dart', linkMode: DynamicLoadingBundled(), file: input.outputDirectory.resolve('libmylib.so'), ), ); // Emit a data asset output.assets.data.add( DataAsset( package: input.packageName, name: 'config.json', file: input.packageRoot.resolve('assets/config.json'), ), ); // Emit metadata for dependent build hooks output.metadata['apiVersion'] = '2'; // Route asset to a specific link hook instead of the app bundle output.assets.code.add( CodeAsset( package: input.packageName, name: 'treeshakeable.dart', linkMode: DynamicLoadingBundled(), file: input.outputDirectory.resolve('libtreeshakeable.so'), ), routing: ToLinkHook(input.packageName), ); }); } ``` -------------------------------- ### Apply Standard Build Settings Source: https://github.com/dart-lang/native/blob/main/pkgs/jni/example/windows/runner/CMakeLists.txt Applies a predefined set of standard build settings to the specified target. This can be customized for applications requiring different build configurations. ```cmake apply_standard_settings(${BINARY_NAME}) ``` -------------------------------- ### Accessing Recorded Data in Link Hooks Source: https://github.com/dart-lang/native/blob/main/pkgs/record_use/README.md This example demonstrates how to access recorded usage data within a link hook. It shows how to iterate through method calls and class instances, extracting specific information like arguments and field values. ```dart void main(List arguments) { link(arguments, (input, output) async { final uses = input.recordedUses; if (uses == null) return; final calls = uses.calls[methodId] ?? []; for (final call in calls) { switch (call) { case CallWithArguments( positionalArguments: [StringConstant(value: final english), ...], ): // Shrink a translations file based on all the different translation // keys. print('Translating to pirate: $english'); case _: print('Cannot determine which translations are used.'); } } final ships = uses.instances[classId] ?? []; for (final ship in ships) { switch (ship) { case InstanceConstantReference( instanceConstant: InstanceConstant( fields: {'name': StringConstant(value: final name)}, ), ): // Include the 3d model for this ship in the application but not // bundle the other ships. print('Pirate ship found: $name'); case _: print('Cannot determine which ships are used.'); } } }); } ``` -------------------------------- ### Define Native Asset Build Hook with hooks.build() Source: https://context7.com/dart-lang/native/llms.txt The build() function is the entry point for hook/build.dart. It reads build configuration, runs a builder callback, and writes output. Use it to compile native code or download assets. ```dart // hook/build.dart import 'package:hooks/hooks.dart'; import 'package:native_toolchain_c/native_toolchain_c.dart'; void main(List args) async { await build(args, (BuildInput input, BuildOutputBuilder output) async { final packageName = input.packageName; final packageRoot = input.packageRoot; // Only build if code assets are requested if (!input.config.buildCodeAssets) return; final cbuilder = CBuilder.library( name: packageName, assetName: '$packageName.dart', sources: ['src/$packageName.c'], includes: ['src/include'], defines: {'VERSION': '"1.0.0"'}, ); await cbuilder.run(input: input, output: output); // Track extra dependency for cache invalidation output.dependencies.add(packageRoot.resolve('config.json')); }); } // Debug: dart run hook/build.dart --config .dart_tool/hooks_runner///input.json ``` -------------------------------- ### Emitting Native Code Assets in Dart Source: https://context7.com/dart-lang/native/llms.txt Use `CodeAsset` to define native shared or static libraries for bundling or linking. This example demonstrates emitting both dynamic and static libraries, specifying package, name, link mode, and file path. ```dart // In hook/build.dart — emit a code asset import 'package:code_assets/code_assets.dart'; import 'package:hooks/hooks.dart'; void main(List args) async { await build(args, (input, output) async { if (!input.config.buildCodeAssets) return; final os = input.config.code.targetOS; final arch = input.config.code.targetArchitecture; final libName = os.dylibFileName('mymath'); // libmymath.so / mymath.dll output.assets.code.add( CodeAsset( package: input.packageName, name: 'mymath.dart', // accessed as package:my_pkg/mymath.dart linkMode: DynamicLoadingBundled(), file: input.outputDirectory.resolve(libName), ), ); // Static linking example output.assets.code.add( CodeAsset( package: input.packageName, name: 'static_math.dart', linkMode: StaticLinking(), file: input.outputDirectory.resolve(os.staticlibFileName('staticmath')), ), ); }); } // In Dart app — use the code asset import 'dart:ffi'; @Native print(add(21, 21)); // 42 ``` -------------------------------- ### Run Hook with Debugger Source: https://github.com/dart-lang/native/blob/main/pkgs/hooks/doc/debugging.md Execute a build hook from its source file and provide the input configuration using the --config flag to enable debugging. ```sh dart run hook/build.dart --config .dart_tool/hooks_runner/your_package_name/some_hash/input.json ``` -------------------------------- ### Objective-C/Dart Reference Cycle Example Source: https://github.com/dart-lang/native/blob/main/pkgs/ffigen/doc/objc_gc.md This code demonstrates a potential memory leak due to a reference cycle between a Dart wrapper object and an Objective-C type. The Dart function implicitly holds a reference back to the Objective-C object, creating a cycle that GC cannot resolve. ```dart final foo = FooInterface(); foo.delegate = BarDelegate.implement( someMethod: () { foo.anotherMethod(); } ); ``` -------------------------------- ### Cross-building Sysroot Configuration Source: https://github.com/dart-lang/native/blob/main/pkgs/jnigen/example/pdfbox_plugin/example/linux/CMakeLists.txt Configures the sysroot and find root path settings for cross-compilation environments. ```cmake if(FLUTTER_TARGET_PLATFORM_SYSROOT) set(CMAKE_SYSROOT ${FLUTTER_TARGET_PLATFORM_SYSROOT}) set(CMAKE_FIND_ROOT_PATH ${CMAKE_SYSROOT}) set(CMAKE_FIND_ROOT_PATH_MODE_PROGRAM NEVER) set(CMAKE_FIND_ROOT_PATH_MODE_PACKAGE ONLY) set(CMAKE_FIND_ROOT_PATH_MODE_LIBRARY ONLY) set(CMAKE_FIND_ROOT_PATH_MODE_INCLUDE ONLY) endif() ``` -------------------------------- ### Configure Output Path with FFIgen YAML Source: https://github.com/dart-lang/native/blob/main/pkgs/ffigen/README.md Specify the output file for generated bindings. Can be a simple string or a more complex object. ```yaml output: 'generated_bindings.dart' ``` ```yaml output: bindings: 'generated_bindings.dart' ... ```