MCPcopy Index your code
hub / github.com/bytedeco/javacpp

github.com/bytedeco/javacpp @1.5.13

Chat with this repo
repository ↗ · DeepWiki ↗ · release 1.5.13 ↗ · + Follow
1,717 symbols 5,046 edges 200 files 577 documented · 34% 3 cross-repo links
What it actually does AI analysis from the code graph — generated when you open this
loading…
README

JavaCPP

Gitter Maven Central Sonatype Nexus (Snapshots) Build Status Commercial support: xscode

Introduction

JavaCPP provides efficient access to native C++ inside Java, not unlike the way some C/C++ compilers interact with assembly language. No need to invent new languages such as with SWIG, SIP, C++/CLI, Cython, or RPython. Instead, similar to what cppyy strives to do for Python, it exploits the syntactic and semantic similarities between Java and C++. Under the hood, it uses JNI, so it works with all implementations of Java SE, in addition to Android, Avian, and RoboVM (instructions).

More specifically, when compared to the approaches above or elsewhere (CableSwig, JNIGeneratorApp, cxxwrap, JNIWrapper, Platform Invoke, GlueGen, LWJGL Generator, JNIDirect, ctypes, JNA, JNIEasy, JniMarshall, JNative, J/Invoke, HawtJNI, JNR, BridJ, CFFI, fficxx, CppSharp, cgo, pybind11, rust-bindgen, Panama Native, etc.), it maps naturally and efficiently many common features afforded by the C++ language and often considered problematic, including overloaded operators, class and function templates, callbacks through function pointers, function objects (aka functors), virtual functions and member function pointers, nested struct definitions, variable length arguments, nested namespaces, large data structures containing arbitrary cycles, virtual and multiple inheritance, passing/returning by value/reference/string/vector, anonymous unions, bit fields, exceptions, destructors and shared or unique pointers (via either try-with-resources or garbage collection), and documentation comments. Obviously, neatly supporting the whole of C++ would require more work (although one could argue about the intrinsic neatness of C++), but we are releasing it here as a proof of concept.

As a case in point, we have already used it to produce complete interfaces to OpenCV, FFmpeg, libdc1394, PGR FlyCapture, OpenKinect, videoInput, ARToolKitPlus, Leptonica, Tesseract, GSL, LLVM, HDF5, MKL, CUDA, Caffe, MXNet, TensorFlow, System APIs, and others as part of the JavaCPP Presets subproject, also demonstrating early parsing capabilities of C/C++ header files that show promising and useful results.

Please feel free to ask questions on the mailing list or the discussion forum if you encounter any problems with the software! I am sure it is far from perfect...

Downloads

Archives containing JAR files are available as releases.

We can also have everything downloaded and installed automatically with:

  • Maven (inside the pom.xml file)
  <dependency>
    <groupId>org.bytedeco</groupId>
    <artifactId>javacpp</artifactId>
    <version>1.5.13</version>
  </dependency>
  • Gradle (inside the build.gradle.kts or build.gradle file)
  dependencies {
    implementation("org.bytedeco:javacpp:1.5.13")
  }
  • Leiningen (inside the project.clj file)
  :dependencies [
    [org.bytedeco/javacpp "1.5.13"]
  ]
  • sbt (inside the build.sbt file)
  libraryDependencies += "org.bytedeco" % "javacpp" % "1.5.13"

Another option available to Gradle users is Gradle JavaCPP, and similarly for Scala users there is SBT-JavaCPP.

Required Software

To use JavaCPP, you will need to download and install the following software:

  • An implementation of Java SE 8 or newer:
  • OpenJDK http://openjdk.java.net/install/ or
  • Oracle JDK http://www.oracle.com/technetwork/java/javase/downloads/ or
  • IBM JDK http://www.ibm.com/developerworks/java/jdk/ or
  • Microsoft JDK https://www.microsoft.com/openjdk etc
  • A C++11 compiler, out of which these have been tested:
  • GNU C/C++ Compiler (Linux, etc.) http://gcc.gnu.org/
    • For Windows x86 and x64 http://mingw-w64.org/
  • LLVM Clang (Mac OS X, etc.) http://clang.llvm.org/
  • Microsoft C/C++ Compiler, part of Visual Studio https://visualstudio.microsoft.com/
    • https://docs.microsoft.com/en-us/cpp/build/walkthrough-compiling-a-native-cpp-program-on-the-command-line

To produce binary files for Android 7.0 or newer, you will also have to install:

  • Android NDK r18 or newer http://developer.android.com/ndk/downloads/

And similarly to target iOS, you will need to install either:

  • Gluon VM http://gluonhq.com/products/mobile/vm/ or
  • RoboVM 1.x or newer http://robovm.mobidevelop.com/downloads/

To modify the source code, please note that the project files were created for:

  • Maven 3.x http://maven.apache.org/download.html

Finally, because we are dealing with native code, bugs can easily crash the virtual machine. Luckily, the HotSpot VM provides some tools to help us debug under those circumstances:

  • Troubleshooting Guide for Java SE with HotSpot VM
  • http://docs.oracle.com/javase/8/docs/technotes/guides/troubleshoot/

Getting Started

To understand how JavaCPP is meant to be used, one should first take a look at the Mapping Recipes for C/C++ Libraries, but a high-level overview of the Basic Architecture is also available to understand the bigger picture. The repository of the JavaCPP Presets further provides complex examples that we can use as templates, but it also includes a wiki page on how to Create New Presets that explains their structure in detail along with a small but complete sample project from which one can start experimenting with.

Key Use Cases

To implement native methods, JavaCPP generates appropriate code for JNI, and passes it to the C++ compiler to build a native library. At no point do we need to get our hands dirty with JNI, makefiles, or other native tools. The important thing to realize here is that, while we do all customization inside the Java language using annotations, JavaCPP produces code that has zero overhead compared to manually coded JNI functions (verify the generated .cpp files to convince yourself). Moreover, at runtime, the Loader.load() method automatically loads the native libraries from Java resources, which were placed in the right directory by the building process. They can even be archived in a JAR file, it changes nothing. Users simply do not need to figure out how to make the system load the files. These characteristics make JavaCPP suitable for either

In addition to the few examples provided below, to learn more about how to use the features of this tool, please refer to the Mapping Recipes for C/C++ Libraries as well as the source code of the JavaCPP Presets for examples. For more information about the API itself, one may refer to the documentation generated by Javadoc.

As a matter of course, this all works with the Scala language as well, but to make the process even smoother, it should not be too hard to add support for "native properties", such that declarations like @native var could generate native getter and setter methods...

Accessing Native APIs

The most common use case involves accessing some native library written for C++, for example, inside a file named NativeLibrary.h containing this C++ class:

#include <string>

namespace NativeLibrary {
    class NativeClass {
        public:
            const std::string& get_property() { return property; }
            void set_property(const std::string& property) { this->property = property; }
            std::string property;
    };
}

To get the job done with JavaCPP, we can easily define a Java class such as this one--although one could use the Parser to produce it from the header file as demonstrated by the JavaCPP Presets subproject, following the principles outlined in the Mapping Recipes for C/C++ Libraries:

import org.bytedeco.javacpp.*;
import org.bytedeco.javacpp.annotation.*;

@Platform(include="NativeLibrary.h")
@Namespace("NativeLibrary")
public class NativeLibrary {
    public static class NativeClass extends Pointer {
        static { Loader.load(); }
        public NativeClass() { allocate(); }
        private native void allocate();

        // to call the getter and setter functions 
        public native @StdString String get_property(); public native void set_property(String property);

        // to access the member variable directly
        public native @StdString String property();     public native void property(String property);
    }

    public static void main(String[] args) {
        // Pointer objects allocated in Java get deallocated once they become unreachable,
        // but C++ destructors can still be called in a timely fashion with Pointer.deallocate()
        NativeClass l = new NativeClass();
        l.set_property("Hello World!");
        System.out.println(l.property());
    }
}

After compiling the Java source code in the usual way, we also need to build using JavaCPP before executing it, or we can let it do everything as follows:

$ java -jar javacpp.jar NativeLibrary.java -exec
Hello World!

Using Complex C++ Types

To demonstrate its relative ease of use even in the face of complex data types, imagine we had a C++ function that took a vector<vector<void*> > as argument. To support that type, we could define a bare-bones class like this: ```java import org.bytedeco.javacpp.; import org.bytedeco.javacpp.annotation.;

@Platform(include="

@Name("std::vector<std::vector<void*> >")
public static class PointerVectorVector extends Pointer {
    static { Loader.load(); }
    public PointerVectorVector()       { allocate();  }
    public PointerVectorVector(long n) { allocate(n); }
    public PointerVectorVector(Pointer p) { super(p); } // this = (vector<vector<void*> >*)p
    private native void allocate();                  // this = new vector<vector<void*> >()
    private native void allocate(long n);            // this = new vector<vector<void*> >(n)
    @Name("operator=")
    public native @ByRef PointerVectorVector put(@ByRef PointerVectorVector x);

    @Name("operator[]")
    public native @StdVector PointerPointer get(long n);
    public native @StdVector PointerPointer at(long n);

    public native long size();
    public native @Cast("bool") boolean empty();
    public native void resize(long n);
    public native @Index long size(long i);                   // return

Extension points exported contracts — how you extend this code

LoadEnabled (Interface)
Classes implementing this interface can access and modify the ClassProperties produced from their {@link Propert [5 implementers]
src/main/java/org/bytedeco/javacpp/LoadEnabled.java
BuildEnabled (Interface)
Classes implementing InfoMapper can additionally implement this interface to receive the logger, properties, and [4 implementers]
src/main/java/org/bytedeco/javacpp/tools/BuildEnabled.java
InfoMapper (Interface)
An interface to define a kind of configuration file entirely written in Java. A class implementing this interface can be [2 …
src/main/java/org/bytedeco/javacpp/tools/InfoMapper.java
ClassFilter (Interface)
An interface used by ClassScanner to determine which classes to load. @author Samuel Audet [1 implementers]
src/main/java/org/bytedeco/javacpp/tools/ClassFilter.java
Indexable (Interface)
An interface implemented to let users access data classes via an Indexer. The class implementing this interface
src/main/java/org/bytedeco/javacpp/indexer/Indexable.java

Core symbols most depended-on inside this repo

index
called by 588
src/main/java/org/bytedeco/javacpp/indexer/Index.java
match
called by 322
src/main/java/org/bytedeco/javacpp/tools/Token.java
get
called by 290
src/main/java/org/bytedeco/javacpp/tools/InfoMap.java
add
called by 180
src/main/java/org/bytedeco/javacpp/tools/DeclarationList.java
equals
called by 174
src/main/java/org/bytedeco/javacpp/tools/Type.java
next
called by 171
src/main/java/org/bytedeco/javacpp/tools/TokenIndexer.java
put
called by 154
src/main/java/org/bytedeco/javacpp/tools/InfoMap.java
create
called by 141
src/main/java/org/bytedeco/javacpp/indexer/Index.java

Shape

Method 1,483
Class 170
Function 42
Enum 15
Interface 7

Languages

Java97%
C++3%

Modules by API surface

src/main/java/org/bytedeco/javacpp/Pointer.java89 symbols
src/test/java/org/bytedeco/javacpp/AdapterTest.java56 symbols
src/main/java/org/bytedeco/javacpp/Loader.java54 symbols
src/main/java/org/bytedeco/javacpp/BytePointer.java49 symbols
src/main/java/org/bytedeco/javacpp/tools/Generator.java48 symbols
src/test/java/org/bytedeco/javacpp/IndexerTest.java39 symbols
src/main/java/org/bytedeco/javacpp/tools/Builder.java39 symbols
src/main/java/org/bytedeco/javacpp/tools/Parser.java37 symbols
src/main/java/org/bytedeco/javacpp/indexer/ByteIndexer.java34 symbols
src/main/java/org/bytedeco/javacpp/tools/NativeAllocationTracer.java31 symbols
src/test/resources/org/bytedeco/javacpp/AdapterTest.h29 symbols
src/test/java/org/bytedeco/javacpp/BufferTest.java26 symbols

For agents

$ claude mcp add javacpp \
  -- python -m otcore.mcp_server <graph>

⬇ download graph artifact