Skip to content
Olivier Chafik edited this page Nov 8, 2022 · 3 revisions

How to use BridJ from Scala

[TOC]

Introduction

BridJ was designed with JNAerator in mind, so that you never have to translate any C / C++ / ObjectiveC header by hand.

JNAerator creates Java sources or classes, that can then be used seamlessly from Scala.

However, BridJ has some Scala-specific features in its core classes, and JNAerator has Scala-specific generation modes.

This page details these Scala-oriented features.

Pointer

BridJ's pointer class was designed to behave like a list, so provided you import scala.collection.JavaConversions._ you'll be able to iterate over its pointed elements.

It also implements apply and update, so indexed access can be made with the natural Scala syntax :

val value = pointer(index)
pointer(index) = value
C code that demonstrates multi-dimensional arrays declarations and usage : ``` float array1d[100]; float array2d[100][200]; float array3d[100][200][300];

float v1 = array1d[10]; float v2 = array2d[10][20]; float v3 = array3d[10][20][30]; array3d[10][20][30] = v1 + v2 + v3;

</td></tr><tr valign="top"><td>
Scala code :

import org.bridj.Pointer._

val array1d = allocateFloats(100) val array2d = allocateFloats(100, 200) val array3d = allocateFloats(100, 200, 300)

val v1 = array1d(10) val v2 = array2d(10)(20) val v3 = array3d(10)(20)(30) array3d(10)(20)(30) = v1 + v2 + v3

</td><td>
Java code :

import org.bridj.Pointer; import static org.bridj.Pointer.*; ... Pointer array1d = allocateFloats(100);

Pointer<Pointer> array2d = allocateFloats(100, 200);

Pointer<Pointer<Pointer>> array3d = allocateFloats(100, 200, 300);

float v1 = array1d.get(10); float v2 = array2d.get(10).get(20); float v3 = array3d.get(10).get(20).get(30); array3d.get(10).get(20).set(30, v1 + v2 + v3);

</td></tr></table>

##  Structs 

When using [JNAerator](http://code.google.com/p/jnaerator/) to create BridJ structs, you can use the `-scalaSetters` switch to generate setters in the form `MyStruct.myField_=` that are treated like setters by Scala.

These setters do not replace the usual generated setters, they're final and just call the usual setters.

<table><tr valign="top"><td colspan="2">
C struct and code :

typedef struct S { int a; double d; } S;

S s; s.a = 10; s.d = 10.0;

</td></tr><tr valign="top"><td>
Scala code :

// Using autogenerated S structure code val s = new S.a(10).d(10.0)

Scala code (using setters) :

val s = new S s.a = 10 s.d = 10.0

</td><td>
Java code :

S s = new S().a(10).d(10.0)

</td></tr></table>
Clone this wiki locally