1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484 485 486 487 488 489 490 491 492 493 494 495 496 497 498 499 500 501 502 503 504 505 506 507 508 509 510 511 512 513 514 515 516 517 518 519 520 521 522 523 524 525 526 527 528 529 530 531 532 533 534 535 536 537 538 539 540 541 542 543 544 545 546 547 548 549 550 551 552 553 554 555 556 557 558 559 560 561 562 563 564 565 566 567 568 569 570 571 572 573 574 575 576 577 578 579 580 581 582 583 584 585 586 587 588 589 590 591 592 593 594 595 596 597 598 599 600 601 602 603 604 605 606 607 608 609 610 611 612 613 614 615 616 617 618 619 620 621 622 623 624 625 626 627 628 629 630 631 632 633 634 635 636 637 638 639 640 641 642 643 644 645 646 647 648 649 650 651 652 653 654 655 656 657 658 659 660 661 662 663 664 665 666 667 668 669 670 671 672 673 674 675 676 677 678 679 680 681 682 683 684 685 686 687 688 689 690 691 692 693 694 695 696 697 698 699 700 701 702 703 704 705 706 707 708 709 710 711 712 713 714 715 716 717 718 719 720 721 722 723 724 725 726 727 728 729 730 731 732 733 734 735 736 737 738 739 740 741 742 743 744 745 746 747 748 749 750 751 752 753 754 755 756 757 758 759 760 761 762 763 764 765 766 767 768 769 770 771 772 773 774 775 776 777 778 779 780 781 782
|
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<title>SWIG and Android</title>
<link rel="stylesheet" type="text/css" href="style.css">
<meta http-equiv="content-type" content="text/html; charset=UTF-8">
</head>
<body bgcolor="#FFFFFF">
<H1><a name="Android">19 SWIG and Android</a></H1>
<!-- INDEX -->
<div class="sectiontoc">
<ul>
<li><a href="#Android_overview">Overview</a>
<li><a href="#Android_examples">Android examples</a>
<ul>
<li><a href="#Android_examples_intro">Examples introduction</a>
<li><a href="#Android_example_simple">Simple C example</a>
<li><a href="#Android_example_class">C++ class example</a>
<li><a href="#Android_examples_other">Other examples</a>
</ul>
<li><a href="#Android_stl">C++ STL</a>
</ul>
</div>
<!-- INDEX -->
<p>
This chapter describes SWIG's support of Android.
</p>
<H2><a name="Android_overview">19.1 Overview</a></H2>
<p>
The Android chapter is fairly short as support for Android is the same as for Java, where the Java Native Interface (JNI) is
used to call from Android Java into C or C++ compiled code.
Everything in the <a href="Java.html#Java">Java chapter</a> applies to generating code for access from Android Java code.
This chapter contains a few Android specific notes and examples.
</p>
<H2><a name="Android_examples">19.2 Android examples</a></H2>
<H3><a name="Android_examples_intro">19.2.1 Examples introduction</a></H3>
<p>
The examples require the <a href="http://developer.android.com/sdk/index.html">Android SDK</a> and <a href="http://developer.android.com/tools/sdk/ndk/index.html">Android NDK</a> which can be installed as per instructions in the links.
The Eclipse version is not required for these examples as just the command line tools are used (shown for Linux as the host, but Windows will be very similar, if not identical in most places).
Add the SDK tools and NDK tools to your path and create a directory somewhere for your Android projects (adjust PATH as necessary to where you installed the tools):
</p>
<div class="shell">
<pre>
$ export PATH=$HOME/android/android-sdk-linux_x86/tools:$HOME/android/android-sdk-linux_x86/platform-tools:$HOME/android/android-ndk-r6b:$PATH
$ mkdir AndroidApps
$ cd AndroidApps
</pre>
</div>
<p>
The examples use a target id of 1. This might need changing depending on your setup.
After installation of the Android SDK, the available target ids can be viewed by running the command below.
Please adjust the id to suit your target device.
</p>
<div class="shell">
<pre>
$ android list targets
</pre>
</div>
<p>
The following examples are shipped with SWIG under the Examples/android directory and include a Makefile to build and install each example.
</p>
<H3><a name="Android_example_simple">19.2.2 Simple C example</a></H3>
<p>
This simple C example shows how to call a C function as well as read and modify a global variable.
First we'll create and build a pure Java Android app. Afterwards the JNI code will be generated by SWIG and built into the app.
First create and build an app called <tt>SwigSimple</tt> in a subdirectory called <tt>simple</tt> using the commands below.
Adjust the <tt>--target</tt> id as mentioned earlier in the <a href="Android.html#Android_examples_intro">Examples introduction</a>.
<a href="http://developer.android.com/guide/developing/projects/projects-cmdline.html">Managing Projects from the Command Line</a> on the Android developer's site is a useful reference for these steps.
</p>
<div class="shell">
<pre>
$ android create project --target 1 --name SwigSimple --path ./simple --activity SwigSimple --package org.swig.simple
$ cd simple
$ ant debug
</pre>
</div>
<p>
Modify <tt>src/org/swig/simple/SwigSimple.java</tt> from the default to:
</p>
<div class="code">
<pre>
package org.swig.simple;
import android.app.Activity;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.TextView;
import android.widget.ScrollView;
import android.text.method.ScrollingMovementMethod;
public class SwigSimple extends Activity
{
TextView outputText = null;
ScrollView scroller = null;
/** Called when the activity is first created. */
@Override
public void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
outputText = (TextView)findViewById(R.id.OutputText);
outputText.setText("Press 'Run' to start...\n");
outputText.setMovementMethod(new ScrollingMovementMethod());
scroller = (ScrollView)findViewById(R.id.Scroller);
}
public void onRunButtonClick(View view)
{
outputText.append("Started...\n");
nativeCall();
outputText.append("Finished!\n");
// Ensure scroll to end of text
scroller.post(new Runnable() {
public void run() {
scroller.fullScroll(ScrollView.FOCUS_DOWN);
}
});
}
/** Calls into C/C++ code */
public void nativeCall()
{
// TODO
}
}
</pre>
</div>
<p>
The above simply adds a <i>Run</i> button and scrollable text view as the GUI aspects of the program.
The associated resources need to be created, modify <tt>res/layout/main.xml</tt> as follows:
</p>
<div class="code">
<pre>
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:orientation="vertical"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
>
<Button
android:id="@+id/RunButton"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Run..."
android:onClick="onRunButtonClick"
/>
<ScrollView
android:id="@+id/Scroller"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
>
<TextView
android:id="@+id/OutputText"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
/>
</ScrollView>
</LinearLayout>
</pre>
</div>
<p>
Rebuild the project with your changes:
</p>
<div class="shell">
<pre>
$ ant debug
</pre>
</div>
<p>
Although there are no native function calls in the code, yet, you may want to check that this simple pure
Java app runs before adding in the native calls.
First, set up your Android device for hardware debugging, see <a href="http://developer.android.com/guide/developing/device.html">Using hardware devices</a> on the Android developer's site.
When complete your device should be listed in those attached, something like:
</p>
<div class="shell">
<pre>
$ adb devices
List of devices attached
A32-6DBE0001-9FF80000-015D62C3-02018028 device
</pre>
</div>
<p>
This means you are now ready to install the application...
</p>
<div class="shell">
<pre>
$ adb install bin/SwigSimple-debug.apk
95 KB/s (4834 bytes in 0.049s)
pkg: /data/local/tmp/SwigSimple-debug.apk
Success
</pre>
</div>
<p>
The newly installed 'SwigSimple' app will be amongst all your other applications on the home screen. Run the app and it will show a <i>Run</i> button text box below it.
Press the <i>Run</i> button to see the simple text output.
</p>
<p>
The application can be uninstalled like any other application and in fact must be uninstalled before installing an updated version. Uninstalling is quite easy too from your host computer:
</p>
<div class="shell">
<pre>
$ adb uninstall org.swig.simple
Success
</pre>
</div>
<p>
Now that you have a pure Java Android app working, let's add some JNI code generated from SWIG.
</p>
<p>
First create a <tt>jni</tt> subdirectory and then create some C source code in <tt>jni/example.c</tt>:
</p>
<div class="code">
<pre>
/* File : example.c */
/* A global variable */
double Foo = 3.0;
/* Compute the greatest common divisor of positive integers */
int gcd(int x, int y) {
int g;
g = y;
while (x > 0) {
g = x;
x = y % x;
y = g;
}
return g;
}
</pre>
</div>
<p>
Create a SWIG interface file for this C code, <tt>jni/example.i</tt>:
</p>
<div class="code">
<pre>
/* File : example.i */
%module example
%inline %{
extern int gcd(int x, int y);
extern double Foo;
%}
</pre>
</div>
<p>
Invoke SWIG as follows:
</p>
<div class="shell">
<pre>
$ swig -java -package org.swig.simple -outdir src/org/swig/simple -o jni/example_wrap.c jni/example.i
</pre>
</div>
<p>
SWIG generates the following files:
</p>
<ul>
<li><tt>src/org/swig/simple/exampleJNI.java</tt></li>
<li><tt>src/org/swig/simple/example.java</tt></li>
<li><tt>jni/example_wrap.c</tt></li>
</ul>
<p>
Next we need to create a standard Android NDK build system file <tt>jni/Android.mk</tt>:
</p>
<div class="code">
<pre>
# File: Android.mk
LOCAL_PATH := $(call my-dir)
include $(CLEAR_VARS)
LOCAL_MODULE := example
LOCAL_SRC_FILES := example_wrap.c example.c
include $(BUILD_SHARED_LIBRARY)
</pre>
</div>
<p>
See the <a href="http://developer.android.com/sdk/ndk/index.html">Android NDK documentation</a> for more on the NDK build system and getting started with the NDK.
A simple invocation of ndk-build will compile the .c files and generate a shared object/system library. Output will be similar to:
</p>
<div class="shell">
<pre>
$ ndk-build
Compile thumb : example <= example_wrap.c
Compile thumb : example <= example.c
SharedLibrary : libexample.so
Install : libexample.so => libs/armeabi/libexample.so
</pre>
</div>
<p>
Now that the C JNI layer has been built, we can write Java code to call into the this layer.
Modify the <tt>nativeCall</tt> method in <tt>src/org/swig/simple/SwigSimple.java</tt> to call the JNI code as follows and add the static constructor to load the system library containing the compiled JNI C code:
</p>
<div class="code">
<pre>
/** Calls into C/C++ code */
public void nativeCall()
{
// Call our gcd() function
int x = 42;
int y = 105;
int g = example.gcd(x, y);
outputText.append("The greatest common divisor of " + x + " and " + y + " is " + g + "\n");
// Manipulate the Foo global variable
// Output its current value
double foo = example.getFoo();
outputText.append("Foo = " + foo + "\n");
// Change its value
example.setFoo(3.1415926);
// See if the change took effect
outputText.append("Foo = " + example.getFoo() + "\n");
// Restore value
example.setFoo(foo);
}
/** static constructor */
static {
System.loadLibrary("example");
}
</pre>
</div>
<p>
Compile the Java code as usual, uninstall the old version of the app if still installed and re-install the new app:
</p>
<div class="shell">
<pre>
$ ant debug
$ adb uninstall org.swig.simple
$ adb install bin/SwigSimple-debug.apk
</pre>
</div>
<p>
Run the app again and this time you will see the output pictured below, showing the result of calls into the C code:
</p>
<center><img src="android-simple.png" alt="Android screenshot of SwigSimple example"></center>
<H3><a name="Android_example_class">19.2.3 C++ class example</a></H3>
<p>
The steps for calling C++ code are almost identical to those in the previous C code example.
All the steps required to compile and use a simple hierarchy of classes for shapes are shown in this example.
</p>
<p>
First create an Android project called <tt>SwigClass</tt> in a subdirectory called <tt>class</tt>.
The steps below create and build a the JNI C++ app.
Adjust the <tt>--target</tt> id as mentioned earlier in the <a href="Android.html#Android_examples_intro">Examples introduction</a>.
</p>
<div class="shell">
<pre>
$ android create project --target 1 --name SwigClass --path ./class --activity SwigClass --package org.swig.classexample
$ cd class
</pre>
</div>
<p>
Now create a <tt>jni</tt> subdirectory and then create a C++ header file <tt>jni/example.h</tt> which defines our
hierarchy of shape classes:
</p>
<div class="code">
<pre>
/* File : example.h */
class Shape {
public:
Shape() {
nshapes++;
}
virtual ~Shape() {
nshapes--;
}
double x, y;
void move(double dx, double dy);
virtual double area() = 0;
virtual double perimeter() = 0;
static int nshapes;
};
class Circle : public Shape {
private:
double radius;
public:
Circle(double r) : radius(r) { }
virtual double area();
virtual double perimeter();
};
class Square : public Shape {
private:
double width;
public:
Square(double w) : width(w) { }
virtual double area();
virtual double perimeter();
};
</pre>
</div>
<p>
and create the implementation in the <tt>jni/example.cpp</tt> file:
</p>
<div class="code">
<pre>
/* File : example.cpp */
#include "example.h"
#define M_PI 3.14159265358979323846
/* Move the shape to a new location */
void Shape::move(double dx, double dy) {
x += dx;
y += dy;
}
int Shape::nshapes = 0;
double Circle::area() {
return M_PI*radius*radius;
}
double Circle::perimeter() {
return 2*M_PI*radius;
}
double Square::area() {
return width*width;
}
double Square::perimeter() {
return 4*width;
}
</pre>
</div>
<p>
Create a SWIG interface file for this C++ code in <tt>jni/example.i</tt>:
</p>
<div class="code">
<pre>
/* File : example.i */
%module example
%{
#include "example.h"
%}
/* Let's just grab the original header file here */
%include "example.h"
</pre>
</div>
<p>
Invoke SWIG as follows, note that the -c++ option is required for C++ code:
</p>
<div class="shell">
<pre>
$ swig -c++ -java -package org.swig.classexample -outdir src/org/swig/classexample -o jni/example_wrap.cpp jni/example.i
</pre>
</div>
<p>
SWIG generates the following files:
</p>
<ul>
<li><tt>src/org/swig/classexample/Square.java</tt></li>
<li><tt>src/org/swig/classexample/exampleJNI.java</tt></li>
<li><tt>src/org/swig/classexample/example.java</tt></li>
<li><tt>src/org/swig/classexample/Circle.java</tt></li>
<li><tt>src/org/swig/classexample/Shape.java</tt></li>
<li><tt>jni/example_wrap.cpp</tt></li>
</ul>
<p>
Next we need to create an Android NDK build system file for compiling the C++ code <tt>jni/Android.mk</tt>.
The <tt>-frtti</tt> compiler flag isn't strictly needed for this example, but is needed for any code that uses C++ RTTI:
</p>
<div class="code">
<pre>
# File: Android.mk
LOCAL_PATH := $(call my-dir)
include $(CLEAR_VARS)
LOCAL_MODULE := example
LOCAL_SRC_FILES := example_wrap.cpp example.cpp
LOCAL_CFLAGS := -frtti
include $(BUILD_SHARED_LIBRARY)
</pre>
</div>
<p>
A simple invocation of ndk-build will compile the .cpp files and generate a shared object/system library. Output will be similar to:
</p>
<div class="shell">
<pre>
$ ndk-build
Compile++ thumb : example <= example_wrap.cpp
Compile++ thumb : example <= example.cpp
StaticLibrary : libstdc++.a
SharedLibrary : libexample.so
Install : libexample.so => libs/armeabi/libexample.so
</pre>
</div>
<p>
Now that the C JNI layer has been built, we can write Java code to call into this layer.
Modify <tt>src/org/swig/classexample/SwigClass.java</tt> from the default to:
</p>
<div class="code">
<pre>
package org.swig.classexample;
import android.app.Activity;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.TextView;
import android.widget.ScrollView;
import android.text.method.ScrollingMovementMethod;
public class SwigClass extends Activity
{
TextView outputText = null;
ScrollView scroller = null;
/** Called when the activity is first created. */
@Override
public void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
outputText = (TextView)findViewById(R.id.OutputText);
outputText.setText("Press 'Run' to start...\n");
outputText.setMovementMethod(new ScrollingMovementMethod());
scroller = (ScrollView)findViewById(R.id.Scroller);
}
public void onRunButtonClick(View view)
{
outputText.append("Started...\n");
nativeCall();
outputText.append("Finished!\n");
// Ensure scroll to end of text
scroller.post(new Runnable() {
public void run() {
scroller.fullScroll(ScrollView.FOCUS_DOWN);
}
});
}
/** Calls into C/C++ code */
public void nativeCall()
{
// ----- Object creation -----
outputText.append( "Creating some objects:\n" );
Circle c = new Circle(10);
outputText.append( " Created circle " + c + "\n");
Square s = new Square(10);
outputText.append( " Created square " + s + "\n");
// ----- Access a static member -----
outputText.append( "\nA total of " + Shape.getNshapes() + " shapes were created\n" );
// ----- Member data access -----
// Notice how we can do this using functions specific to
// the 'Circle' class.
c.setX(20);
c.setY(30);
// Now use the same functions in the base class
Shape shape = s;
shape.setX(-10);
shape.setY(5);
outputText.append( "\nHere is their current position:\n" );
outputText.append( " Circle = (" + c.getX() + " " + c.getY() + ")\n" );
outputText.append( " Square = (" + s.getX() + " " + s.getY() + ")\n" );
// ----- Call some methods -----
outputText.append( "\nHere are some properties of the shapes:\n" );
Shape[] shapes = {c, s};
for (int i=0; i<shapes.length; i++)
{
outputText.append( " " + shapes[i].toString() + "\n" );
outputText.append( " area = " + shapes[i].area() + "\n" );
outputText.append( " perimeter = " + shapes[i].perimeter() + "\n" );
}
// Notice how the area() and perimeter() functions really
// invoke the appropriate virtual method on each object.
// ----- Delete everything -----
outputText.append( "\nGuess I'll clean up now\n" );
// Note: this invokes the virtual destructor
// You could leave this to the garbage collector
c.delete();
s.delete();
outputText.append( Shape.getNshapes() + " shapes remain\n" );
outputText.append( "Goodbye\n" );
}
/** static constructor */
static {
System.loadLibrary("example");
}
}
</pre>
</div>
<p>
Note the static constructor and the interesting JNI code is in the <tt>nativeCall</tt> method.
The remaining code deals with the GUI aspects which are identical to the previous C simple example. Modify <tt>res/layout/main.xml</tt> to contain the xml for the 'Run' button and scrollable text view:
</p>
<div class="code">
<pre>
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:orientation="vertical"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
>
<Button
android:id="@+id/RunButton"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Run..."
android:onClick="onRunButtonClick"
/>
<ScrollView
android:id="@+id/Scroller"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
>
<TextView
android:id="@+id/OutputText"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
/>
</ScrollView>
</LinearLayout>
</pre>
</div>
<p>
Compile the Java code as usual, uninstall the old version of the app if installed and re-install the new app:
</p>
<div class="shell">
<pre>
$ ant debug
$ adb uninstall org.swig.classexample
$ adb install bin/SwigClass-debug.apk
</pre>
</div>
<p>
Run the app to see the result of calling the C++ code from Java:
</p>
<center><img src="android-class.png" alt="Android screenshot of SwigClass example"></center>
<H3><a name="Android_examples_other">19.2.4 Other examples</a></H3>
<p>
The Examples/android directory contains further examples which can be run and installed in a similar manner to the previous two examples.
</p>
<p>
Note that the 'extend' example is demonstrates the directors feature.
Normally C++ exception handling and the STL is not available by default in the version of g++ shipped with Android, but this example turns these features on as described in the next section.
</p>
<H2><a name="Android_stl">19.3 C++ STL</a></H2>
<p>
Should the C++ Standard Template Library (STL) be required, an <tt>Application.mk</tt> file needs to be created
in the same directory as the <tt>Android.mk</tt> directory containing information about the STL to use.
See the NDK documentation in the $NDKROOT/docs folder especially CPLUSPLUS-SUPPORT.html.
Below is an example of the <tt>Application.mk</tt> file to make the STLport static library available for use:
</p>
<div class="code">
<pre>
# File: Application.mk
APP_STL := gnustl_static
</pre>
</div>
</body>
</html>
|