Contenu connexe Similaire à Using the NDK and Renderscript Similaire à Using the NDK and Renderscript (20) Plus de Motorola Mobility - MOTODEV Plus de Motorola Mobility - MOTODEV (20) Using the NDK and Renderscript1. Motorola Mobility
Peter van der Linden
Android Technology Evangelist
Developer Platforms and Services
Faster and Faster Graphics – Using the
NDK and RenderScript
Version 1.0
2. 1 INSTALLING THE TOOLS
2 WRITE YOUR C CODE
3 BUILD YOUR C CODE
4 CALLING C FROM JAVA (the JNI)
5 SUMMARY - Wrap up, Q & A
© 2011 Motorola Mobility, Inc. Version 1.0
3. Page 3
WHY C/C++ CODE ON ANDROID?
• Open GL
• Performance
• Porting!
© 2011 Motorola Mobility, Inc. Version 1.0
4. Page 4
NDK C++ limitations
• Originally for writing performance-critical parts of code in C
You don’t need OOP abstraction for that.
(And Dalvik VM is pretty fast, with JIT compiling since 2.2)
• C++ support is somewhat restricted
exceptions are not supported
known bugs in static constructor/destructor invocations.
• So NDK code is more likely to be written in C rather than C++.
© 2011 Motorola Mobility, Inc. Version 1.0
5. Page 5
SUPPORTED CPU architectures
NDK supports two ARM instruction sets:
• ARMv5TE (includes Thumb-1 instructions). This is the
default target, and code compiled for this will run on all ARM-
based Android devices. Choose other target, by changing one
line in the Application.mk makefile.
• ARMv7-A (includes Thumb-2 and VFPv3-D16 instructions,
with optional support for NEON/VFPv3-D32 instructions). Code
compiled for ARMv7-A will run only on devices such as the
Verizon Droid or Motorola XOOM that have a v7 CPU. Code
for NEON will only run on an ARMv7 with support for NEON.
There’s a third architecture “in the works” (experimental, no
support)
• x86 instruction set
© 2011 Motorola Mobility, Inc. Version 1.0
6. INSTALLING THE TOOLS
MOTOROLA and the Stylized M Logo are trademarks or registered trademarks of Motorola Trademark Holdings, LLC. Version 1.0
All other trademarks are the property of their respective owners. © 2011 Motorola Mobility, Inc. All rights reserved.
7. Page 7
Downloading the Native Development Kit
• Check compatibility: XP or Vista, MacOS X 10.5, Ubuntu
• Download the 50 MB zip or tar.bz2 file from:
http://developer.android.com/sdk/ndk/index.html
• Uncompress it anywhere; remember where in $NDK
export NDK=~/andro id-ndk-r5b
• Requires GNU make and GNU awk! Windows users –
install Cygwin 1.7 or later
© 2011 Motorola Mobility, Inc. Version 1.0
8. Page 8
Windows users
• Download and install Cygwin 1.7 or later
• Unix/Linux command line tools for Windows users
http://cygwin.com
© 2011 Motorola Mobility, Inc. Version 1.0
9. Page 9
Windows and MacOS X tips
• Don’t use pathnames with spaces in them! Anywhere!
• Cygwin only installs the base packages
• You need the development packages. Simplest to install
the entire Devel branch.
1. Run setup.exe
2.Click the word “Default” next to the root Devel node
3. “Default” changes to “Install” for the Devel node
4. Click “next” to install. Go to lunch while it installs
5. Let it create a cygwin console icon on your desktop
6. Type “make –v” in the cygwin console to check it’s OK.
© 2011 Motorola Mobility, Inc. Version 1.0
10. Page 10
Unpack the Native Development Kit
• Gives you 7 folders, and a bunch of things to read
© 2011 Motorola Mobility, Inc. Version 1.0
11. Page 11
NDK folders
• build – 4 folders of awk & shell scripts, makefiles to build your C/C++ files
• docs – about 20 text files (FAQs on NDK). Access it thru browsing
documentation.html
• platforms – .h and system library.so files for the various API levels
• samples – a dozen working samples
• sources – some sources for systemy things
• tests – scripts to test the NDK itself. Probably in here by mistake.
• toolchains – cross-compiler toolchains
© 2011 Motorola Mobility, Inc. Version 1.0
12. Page 12
Add C/C++ support into Eclipse
• Eclipse has a plugin for C/C++, just like for Android
• Get it using Eclipse
Help > Install new software
•Type http://download.eclipse.org/releases/helios/
in “work with” field (or whatever release you use)
• Usual caveats about network proxies at work (set them
under MOTODEV Studio > Preferences > Network Conn. )
• Click Programming Langs > C/C++ Development Tools
© 2011 Motorola Mobility, Inc. Version 1.0
13. Page 13
• There’s a plugin for C/C++, just like for Android
• Get it using Eclipse
Help > Install new software
© 2011 Motorola Mobility, Inc. Version 1.0
14. Write your C code
MOTOROLA and the Stylized M Logo are trademarks or registered trademarks of Motorola Trademark Holdings, LLC. Version 1.0
All other trademarks are the property of their respective owners. © 2011 Motorola Mobility, Inc. All rights reserved.
15. Page 15
General Approach
• You start with a Java Android app, and add NDK pieces to it.
• put your native C/C++ sources in $PROJECT/jni:
• build your native code into libraries
• Your Android Java code can call into these native libraries
• Native code can also call back into Java, and access Java objects
© 2011 Motorola Mobility, Inc. Version 1.0
16. Page 16
Create the Android project
as usual
© 2011 Motorola Mobility, Inc. Version 1.0
17. Page 17
Create the jni folder for your project
• Highlight the Eclipse project that will use native code
• Your package name is used to access the native code, so keep
it short and simple. e.g. “com.greet” for training purposes
• File > New > Folder give it the name “jni”
• Inside that newly-created jni folder, we will add
• a makefile
• some C files
© 2011 Motorola Mobility, Inc. Version 1.0
18. Page 18
Add two files to the jni folder in your project
• File > New > Other …
• Select “General” then “file” then browse
• Choose the jni folder, with a filename of “Android.mk” > Finish
• Repeat, creating a file “myhello.c”, also in the jni folder
• That gives you
jni/Android.mk
jni/myhello.c
© 2011 Motorola Mobility, Inc. Version 1.0
19. Page 19
Populate the jni folder infolder project
Creating files in the jni your
greet
© 2011 Motorola Mobility, Inc. Version 1.0
21. Page 21
Fill in the Android.mk makefile
• Edit file jni/Android.mk that you just created
• Put these magic words into the makefile
LOCAL_PATH := $ l my-d r
(cal i)
i lude $
nc (CLEAR_VARS)
# our source fl and t l rary bu l f
ie he ib it rom it
LOCAL_M O D ULE : he lo
= l
LOCAL_SRC_FILES : he lo c
= l .
i lude $
nc (BUILD_SHARE D_LIBRARY)
© 2011 Motorola Mobility, Inc. Version 1.0
22. Page 22
Diversion about make
• Make was created by Stu Feldman in 1977 at Bell Labs
• In 2003, Dr. Feldman received the ACM Software System
Award for authoring this widespread tool.
• You didn’t hear it from me, but software lore has it that …
# Each command that follows dependency line,
# i.e. the TARGET to the left, must be indented by a TAB character.
target: component-to-build
<TAB>commands-to-build-it
© 2011 Motorola Mobility, Inc. Version 1.0
23. Page 23
Create the C code in your jni folder
• Edit file jni/myhello.c that you just created
• Put these magic words into the C file
• Uses the JNIEnv object to create a Java string from a literal
#include <string.h>
#include <jni.h>
jstring Java_com_greet_MyActivity_myCFunction
(JNIEnv* env, jobject javaThis) {
return (*env)->NewStringUTF(env, "Hello from native code!");
}
© 2011 Motorola Mobility, Inc. Version 1.0
24. Page 24
C code explained
When the JVM invokes a native function, it passes
• a JNIEnv pointer, (structure that has the interface to JVM for C)
• a jobject pointer, (the “this” object)
• any Java arguments declared by the Java method.
These types come from #include <jni.h> (look under “platforms”)
Your C method must be written to expect these args
The C method is named “Java” _classname_activity_methodname
#include <string.h>
#include <jni.h>
jstring Java_com_greet_MyActivity_myCFunction
(JNIEnv* env, jobject javaThis) {
return (*env)->NewStringUTF(env, "Hello from native code!");
}
• … looks like, but isn’t, a memory leak?
© 2011 Motorola Mobility, Inc. Version 1.0
25. Build your C code
MOTOROLA and the Stylized M Logo are trademarks or registered trademarks of Motorola Trademark Holdings, LLC. Version 1.0
All other trademarks are the property of their respective owners. © 2011 Motorola Mobility, Inc. All rights reserved.
26. Page 26
CALLING BETWEEN LANGUAGES
• Android follows the standard way to talk between Java and C
• JNI – Java Native Interface
• Link to JNI docs http://java.sun.com/docs/books/jni/
• That includes a complete book, a tutorial, examples etc.
© 2011 Motorola Mobility, Inc. Version 1.0
27. Page 27
Build your C library
• Bring up a terminal window, and cd into your project jni folder
• Use “ndk-build” script from the NDK directory (just a wrapper
round GNU Make) (can put $NDK in your path, if you want)
• The script compiles your C code, makes it into a shared library
• Moves the libhello.so into a new project folder libs/armeabi
© 2011 Motorola Mobility, Inc. Version 1.0
28. Page 28
General approach for building a library
• Save files in Eclipse
• Bring up a terminal window, and cd into your project jni folder
• Run the ndk-build script to turn your C code into a .so
• That lib*.so will be added into the app’s .apk file
• File > Refresh in Eclipse (to sync with filesystem)
$ cd MYECLIPSEPROJECT/ i
jn
$ $NDK/ndk-bu ld
i
Co mpi e thumb : he l <= helo
l lo l .c
SharedL ibrary :l bhe l
i lo.so
Ins l
tal :l b l .so => l /armeab /ibhe lo
i he lo ibs il l .so
© 2011 Motorola Mobility, Inc. Version 1.0
29. Page 29
BUILD YOUR LIBRARY - summary
• Eclipse doesn’t build your NDK code, GNU Make does
• The C/C++ plugin gives you syntax colors and editing (only)
• Run the “ndk-build” script after each edit of your C code
• Then click File > Refresh, (F5), to keep Eclipse in sync with your native files.
© 2011 Motorola Mobility, Inc. Version 1.0
30. The Java End of JNI
MOTOROLA and the Stylized M Logo are trademarks or registered trademarks of Motorola Trademark Holdings, LLC. Version 1.0
All other trademarks are the property of their respective owners. © 2011 Motorola Mobility, Inc. All rights reserved.
31. Page 31
Java code that calls to the native code
• Start with the basic app that Eclipse gives you
package com.greet;
impor andro
t id.app.Actvt ;
iiy
impor andro
t id.os.Bund ;
le
pub ic cl
l ass MyAct i y ex
ivt tends Ac ivt {
t iy
/ * Ca led when the ac i i y i fr tcrea
* l t vt s i s ted.*/
@ Over ide
r
pub i vo onCreate
lc id (Bund savedIns
le tanceSta e) {
t
super .onCreate(savedInstanceSta te);
setContentV iew(R.layout in)
.ma ;
}
}
© 2011 Motorola Mobility, Inc. Version 1.0
32. Page 32
Add the library load
• Add the call to load our native library libhello.so
• name must match library name without “lib” and “.so”
• so libhello.so is “hello”
s t {
ta ic
Sys em.
t loadLibrary( l )
”he lo" ;
}
© 2011 Motorola Mobility, Inc. Version 1.0
33. Page 33
Add the declaration of the native function
• Add the prototype declaration of the C function
• On the C side, it has two explicit arguments, an envp, a this
• But on the Java side, those arguments are implicit
p iva na i Str myCFunct )
r te t ve ing ion( ;
© 2011 Motorola Mobility, Inc. Version 1.0
34. Page 34
Add the call to the native function
• We’re going to get the string from C, and toast it.
impor s t c andro .
t ta i id widget Toast *
. .;
impor andro
t id.widget.Toas ;
t
...
Sr
t ing msg = myCFunct )
ion( ;
Toas .
t makeText th msg, LEN GTH_LO N G).show()
( is, ;
© 2011 Motorola Mobility, Inc. Version 1.0
35. Page 35
Putting it all together
package com.greet
;
impor andro .app.Ac ivt ;
t id t iy
impor andro .os Bund ;
t id . le
impor s i andro d.w
t tatc i idget Toast *
. .;
impor andro .w
t id idget.Toas ;
t
pub ic c
l lass MyAct v ty ex
ii tends Ac ivt {
t iy
s t c { Sys
ta i tem.loadLibrary " l " ;}
( he lo )
pr te natve S r
iva i t ing myCFunct )
ion( ;
@ Override
pub i vo onCreate(Bund savedIns
l c id le tanceSta {
te)
super.onCreate(savedInstanceState);
setConten iew(R.
tV layout in)
.ma ;
Sr
t ing msg = myCFunct )
ion( ;
Toas .makeText th ,msg, LENGT H_LON G).show()
t ( is ;
}
}
© 2011 Motorola Mobility, Inc. Version 1.0
38. Page 38
THE BEGINNING
This may be a beautiful beginning to a long road
• http://groups.google.com/group/android-
ndk/topics
• http://java.sun.com/docs/books/jni/
• http://developer.android.com/sdk/ndk/index.htm
l
© 2011 Motorola Mobility, Inc. Version 1.0
39. Page 39
Page
Renderscript
• New, high performance 3D graphics
API
• Was used in Froyo for Live Wallpaper
• Is used in Honeycomb for Books and
YouTube app
• Honeycomb introduces Renderscript
as a public API
• For performance critical code where
the traditional Open GL ES framework
APIs are not fast enough!
© 2010 Motorola Mobility, Inc. Version 1.0
© 2011 Motorola Mobility, Inc. Version 1.0
40. Page 40
Page
YouTube and Renderscript
© 2010 Motorola Mobility, Inc. Version 1.0
© 2011 Motorola Mobility, Inc. Version 1.0
41. Page 41
Page
Books and Renderscript
© 2010 Motorola Mobility, Inc. Version 1.0
© 2011 Motorola Mobility, Inc. Version 1.0
42. Page 42
Page
Renderscript API
• A “computing” API for locating moving points in 3D
• A “rendering” API for drawing textures over the points
• A C-based scripting language to access this API
• Only goal: squeeze last ounce of graphics performance!
• Approach: API is a thin layer over features that are hardware-supported
• http://community.developer.motorola.com/t5/MOTODEV-
Blog/Introduction-to-Renderscript/ba-p/12136
© 2010 Motorola Mobility, Inc. Version 1.0
© 2011 Motorola Mobility, Inc. Version 1.0
43. Page 43
Page
Renderscript API
• Android build tools compile your Renderscript .rs file to intermediate
bytecode
• and package it inside your application's .apk file
• On the device, the bytecode is compiled (just-in-time) to machine code
that is optimized for the exact device that it is running on
• Machine code is cached for future use
• This eliminates the need to target a specific architecture during the
development process. Excellent!
© 2011 Motorola Mobility, Inc. Version 1.0
44. Page 44
Page
Example .rs file (from Honeycomb samples)
#pragma rsjava_package_name(com.andro . s l
id r .he lowor )
ld
# lude "
inc rs_graph cs rsh”/ header w th g
i . / i raphics API’s
/ gTouchX and gTouchY are var les tha w l be re lec ed fo use
/ iab t il f t r
/ by the j
/ ava API W e can use them t no i y the scr t o touch events
. o tf ip f .
i t gTouchX;
n
i t gTouchY;
n
/ Th i i
/ is s nvoked automat l when t scr ti c ted
icaly he ip s rea
vo int ){
id i(
gTouchX = 50 ;
.0f
gTouchY = 50 ;
.0f
}
i troo (
n t intlaunchID) {
/ C
/ lear the background co lor
rsgClearCo (0.0 , 0 f 0.0 , 0 f ;
lor f .0 , f .0 )
/ Te lt run ime what the fon co or shou be
/ l he t t l ld
rsgFontCo r .0f 1 f 1 0f 1 f ;
lo (1 , .0 , . , .0 )
/ In roduce ourse
/ t lves to t wor by drawing a g tng
he ld ree i
/ a the pos t user touched on the screen
/ t iion
rsgDrawText "He lo Wor d! , gTouchX, gTouchY)
( l l " ;
/ Return va tels RS rough how of to r
/ lue l ly ten edraw
/ in th s case 20 ms
/ i
re rn 20;
tu
}
© 2011 Motorola Mobility, Inc. Version 1.0
Version 1.0
45. Page 45
Licenses
Source code examples displayed in this presentation may be licensed under Apache License,
Version 2 as follows:
Copyright © 2010, Android Open Source Project. All rights reserved unless otherwise explicitly
indicated.
Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in
compliance with the License. You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0.
Unless required by applicable law or agreed to in writing, software distributed under the License is
distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either
express or implied. See the License for the specific language governing permissions and limitations
under the License.
© 2011 Motorola Mobility, Inc. Version 1.0
46. Page 46
Licenses
Source code examples displayed in this presentation may be licensed under BSD License, as
follows:
Copyright © 2010-2011, Motorola, Inc. All rights reserved except as otherwise explicitly indicated.
Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following
conditions are met:
Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer.
Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following
disclaimer in the documentation and/or other materials provided with the distribution.
Neither the name of the Motorola, Inc. nor the names of its contributors may be used to endorse or promote products
derived from this software without specific prior written permission.
THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS
OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF
MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE
COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL,
EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR
TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
© 2011 Motorola Mobility, Inc. Version 1.0