SlideShare a Scribd company logo
1 of 45
Download to read offline
Android and C++ 
Joan Puig Sanz
About me 
@joanpuigsanz 
2
What we will see? 
1. Apps for all the platforms 
2. C++ 11 
3. Libraries 
4. Java, C++ and JNI 
5. Final thoughts 
3
Text 
The same app running in all the platforms 
4
5
Most common solutions? 
PhoneGap Adobe Air 
Xamarin 
Titanium 
6
7
✦ Not native UI 
✦ Slow performance 
✦ Custom components. 
✦ Depend on a company 
✦ Poor user experience 
8
Good user experience 
Smooth 
UI 
UX 
9
Text 
An other old solution… 
C++ 10
Why C++? 
Cross platform 
language 
Better performance 
Mature language 
Lots of libraries 
11
Combining C++ with Android 
Native UI and UX 
JNI 
C++ core 
12
Text 
C++ 11 features 
13
C++11 Features :: Auto 
The compiler deducing the type 
auto i = 42; // i is an int 
auto l = 42LL; // l is an long long 
auto p = new Foo(); // p is a foo* 
std::map<std::string, std::vector<int>> map; 
for(auto it = begin(map); it != end(map); ++it) 
{} 
14
C++11 Features :: 
Range-based for loops 
Iterate collections with foreach 
std::vector<int> v; 
v.push_back(1); 
v.push_back(2); 
v.push_back(3); 
for (auto value : v) { 
std::cout << value << std::endl; 
} 
15
C++11 Features :: 
Smart pointers 
unique_ptr: Ownership of a memory resource it is 
not shared, but it can be transferred to another 
unique_ptr 
shared_ptr: Ownership of a memory resource 
should be shared 
weak_ptr: Holds a reference to an object managed 
by a shared_ptr, but does not contribute to the 
reference count; it is used to break dependency cycles. 
16
C++11 Features :: Lambdas 
Powerful feature borrowed from functional 
programming. 
You can use lambdas wherever a function object or a 
functor or a std::function is expected 
std::function<int(int)> lfib = [&lfib](int n) { 
return n < 2 ? 1 : lfib(n-1) + lfib(n-2); 
}; 
17
C++11 Features :: More 
Final and override 
non-member begin() and end() 
Initializer lists 
Object construction improvement 
Unrestricted unions 
User-defined literals 
static_assert 
Strongly-typed enums 
… 
18
Text 
Complementing C++ 
Libraries 
19
Complementing C++ 
C++11 standard library is 
missing utilities: 
HTTP Requests 
XML and JSON 
Big numbers 
Security 
Math 
20
C++ libs :: Boost 
Supports: 
Licence: 
AS IS 
Big community 
Lots of modules 
21
C++ libs :: Juce 
Supports: 
No WP (for now) 
Licence: 
Core: AS IS 
Other modules: GPL and commercial licence 
Very well written code 
Easy to use 
22
C++ libs :: Qt 
Supports: 
Licence: 
GPL and commercial licence 
Big community 
Lots of modules 
23
Text 
Putting stuff together 
JNI 
24
Calling JNI from Java 
Declare native methods 
private native void doSomethingNative (String str); 
Implement C method 
JNIEXPORT void Java_com_example_MyClass_doSomethingNative (JNIEnv 
*env, jobject obj, jstring s) 
{ 
const char* const utf8 = env->GetStringUTFChars (s, nullptr); 
CharPointer_UTF8 utf8CP (utf8); 
String cppString (utf8CP); 
env->ReleaseStringUTFChars (s, utf8); 
// Do Something 
} 
25
Calling JNI from Java 
JNIEXPORT void Java_com_example_MyClass_doSomethingNative 
(JNIEnv *env, 
jobject obj, 
jstring s) 
Required macro to support Windows 
Java + package_name + 
className + methodName 
26
Calling C from Java 
JNIEXPORT void Java_com_example_MyClass_doSomethingNative 
(JNIEnv *env, 
jobject obj, 
jstring s) 
Structure to access all the JNI functions 
Java object that calls the native function 
Java method arguments 
27
Local and global references 
Local reference will be managed by java 
A global reference is managed by the 
developer 
Max number 
of java 
references 
= 512 
28
Calling Java from C 
public String myMethod (int[] array, boolean enabled) 
29
Calling Java from C 
public String myMethod (int[] array, boolean enabled) 
JNIEnv* env = getEnv(); 
jclass myJavaClass = env->GetObjectClass (myJavaObject); 
jmethodID myJavaMethod = env->GetMethodID(myJavaClass , 
”methodName", "([I;Z)Ljava/lang/String"); 
jstring jresult = (jstring) env->CallObjectMethod 
(myJavaObject, myJavaMethod , myIntArray, myBoolean); 
// Do something 
env->DeleteLocalRef (jresult); 
env->DeleteLocalRef (myJavaClass); 
30
Calling Java from C 
public String myMethod (int[] array, boolean enabled) 
JNIEnv* env = getEnv(); 
jclass myJavaClass = env->GetObjectClass(myJavaObject); 
jmethodID myJavaMethod = env->GetMethodID(myJavaClass , 
”methodName", "([I;Z)Ljava/lang/String"); 
jstring jresult = (jstring) env->CallObjectMethod 
(myJavaObject, myJavaMethod , myIntArray, myBoolean); 
// Do something 
env->DeleteLocalRef (jresult); 
env->DeleteLocalRef (myJavaClass); 
Must not be NULL 
This is the java object that has the method 
31
Calling Java from C 
public String myMethod (int[] array, boolean enabled) 
JNIEnv* env = getEnv(); 
jclass myJavaClass = env->GetObjectClass(myJavaObject); 
jmethodID myJavaMethod = env->GetMethodID(myJavaClass, 
”myMethod", "([I;Z)Ljava/lang/String"); 
jstring jresult = (jstring) env->CallObjectMethod 
(myJavaObject, myJavaMethod , myIntArray, myBoolean); 
// Do something 
env->DeleteLocalRef Method signature 
(jresult); 
env->DeleteLocalRef (myJavaClass); 
32
Calling Java from C 
public String myMethod (int[] array, boolean enabled) 
JNIEnv* env = getEnv(); 
jclass myJavaClass = env->GetObjectClass(myJavaObject); 
jmethodID myJavaMethod = env->GetMethodID(myJavaClass, 
”myMethod", "([I;Z)Ljava/lang/String"); 
jstring jresult = (jstring) env->CallObjectMethod 
(myJavaObject, myJavaMethod , myIntArray, myBoolean); 
// Do something 
env->DeleteLocalRef Method signature 
(jresult); 
env->DeleteLocalRef (myJavaClass); 
Type Signature Java Type 
Z Boolean 
B byte 
C char 
S short 
I int 
J long 
F float 
D double 
L class ; full qualified 
[type; tcylpases[] 
33
Calling Java from C 
public String myMethod (int[] array, boolean enabled) 
JNIEnv* env = getEnv(); 
jclass myJavaClass = env->GetObjectClass(myJavaObject); 
jmethodID myJavaMethod = env->GetMethodID(myJavaClass, 
”myMethod", "([I;Z)Ljava/lang/String"); 
jstring jresult = (jstring) env->CallObjectMethod 
(myJavaObject, myJavaMethod , myIntArray, myBoolean); 
// Do something 
env->DeleteLocalRef Method signature 
(jresult); 
env->DeleteLocalRef (myJavaClass); 
34
Calling Java from C 
public String myMethod (int[] array, boolean enabled) 
JNIEnv* env = getEnv(); 
jclass myJavaClass = env->GetObjectClass(myJavaObject); 
jmethodID myJavaMethod = env->GetMethodID(myJavaClass , 
”myMethod", "([I;Z)Ljava/lang/String"); 
jstring jresult = (jstring) env->CallObjectMethod 
(myJavaObject, myJavaMethod , myIntArray, myBoolean); 
// Do something 
env->DeleteLocalRef (jresult); 
env->DeleteLocalRef (myJavaClass); 
35
Calling Java from C 
public String myMethod (int[] array, boolean enabled) 
JNIEnv* env = getEnv(); 
jclass myJavaClass = env->GetObjectClass(myJavaObject); 
jmethodID myJavaMethod = env->GetMethodID(myJavaClass , 
”myMethod", "([I;Z)Ljava/lang/String"); 
jstring jresult = (jstring) env->CallObjectMethod 
(myJavaObject, myJavaMethod , myIntArray, myBoolean); 
// Do something 
env->DeleteLocalRef (jresult); 
env->DeleteLocalRef (myJavaClass); 
36
Java and C++ object binding 
37
Java and C++ object binding 
Java (OO) 
C 
C++ (OO) 
38
Java and C++ object binding 
Java (OO) 
C 
C++ (OO) 
39
Foo Java implementation 
public class Foo { 
native void destroyCppInstanceNative(double ref); 
native long newCppInstanceNative(); 
native String getStringNative(double ref); 
private double _ref = 0; 
public Foo() { 
_ref = newCppInstanceNative(); 
} 
public String getString() { 
return getStringNative(_ref); 
} 
public void destroy() { 
destroyCppInstanceNative(_ref); 
} 
} 40
Foo Java implementation 
JNIEXPORT long Java_com_example_Foo_newCppInstanceNative(JNIEnv 
*env, jobject obj) { 
Foo* newFoo = new Foo(); 
return (double)(newFoo); 
} 
JNIEXPORT jstring Java_com_example_Foo_getStringNative(JNIEnv 
*env, jobject obj, double ref) { 
Foo* foo = (Foo*)(ref); 
jstring jStringResult = env->NewStringUTF (foo->getString()); 
return jStringResult; 
} 
JNIEXPORT void 
Java_com_example_Foo_destroyCppInstanceNative(JNIEnv *env, jobject 
obj, double ref) { 
Foo* foo = (Foo*)(ref); 
delete foo; 
} 
41
Text 
Some advice to live happier with C++ 
42
Some advice 
Code quality! (Code conventions, code reviews, 
etc.) 
C++ is not a read only code, don’t put the blame on 
it 
Remember to initialise all the values in the 
constructor 
Use unity builds to speed up compilation time 
JNI could be painful. Check out djinni to generate 
cross-language type declarations and interface 
bindings. 
dropbox/djinni 
43
Final thoughts 
Pros 
Same core and with native UI/UX per platform 
Better performance 
Faster cross platform development 
Easier maintenance 
Cons 
Need to learn a new language 
Android apps will be bigger (code compiled 
for different architectures) 
Can be fixed distributing specific apk per 
each architecture 44
?@joanpuigsanz 
45

More Related Content

What's hot

3150 Chapter 2 Part 1
3150 Chapter 2 Part 13150 Chapter 2 Part 1
3150 Chapter 2 Part 1
Mole Wong
 
Разработка кросс-платформенного кода между iPhone &lt; -> Windows с помощью o...
Разработка кросс-платформенного кода между iPhone &lt; -> Windows с помощью o...Разработка кросс-платформенного кода между iPhone &lt; -> Windows с помощью o...
Разработка кросс-платформенного кода между iPhone &lt; -> Windows с помощью o...
Yandex
 

What's hot (20)

Easy native wrappers with SWIG
Easy native wrappers with SWIGEasy native wrappers with SWIG
Easy native wrappers with SWIG
 
Introduction to OpenCV (with Java)
Introduction to OpenCV (with Java)Introduction to OpenCV (with Java)
Introduction to OpenCV (with Java)
 
Summary of C++17 features
Summary of C++17 featuresSummary of C++17 features
Summary of C++17 features
 
The Present and The Future of Functional Programming in C++
The Present and The Future of Functional Programming in C++The Present and The Future of Functional Programming in C++
The Present and The Future of Functional Programming in C++
 
Introduction to OpenCV 3.x (with Java)
Introduction to OpenCV 3.x (with Java)Introduction to OpenCV 3.x (with Java)
Introduction to OpenCV 3.x (with Java)
 
3150 Chapter 2 Part 1
3150 Chapter 2 Part 13150 Chapter 2 Part 1
3150 Chapter 2 Part 1
 
Interfacing C/C++ and Python with SWIG
Interfacing C/C++ and Python with SWIGInterfacing C/C++ and Python with SWIG
Interfacing C/C++ and Python with SWIG
 
Async await in C++
Async await in C++Async await in C++
Async await in C++
 
С++ without new and delete
С++ without new and deleteС++ without new and delete
С++ without new and delete
 
10 reasons to be excited about go
10 reasons to be excited about go10 reasons to be excited about go
10 reasons to be excited about go
 
Introduction to D programming language at Weka.IO
Introduction to D programming language at Weka.IOIntroduction to D programming language at Weka.IO
Introduction to D programming language at Weka.IO
 
AOT-compilation of JavaScript with V8
AOT-compilation of JavaScript with V8AOT-compilation of JavaScript with V8
AOT-compilation of JavaScript with V8
 
Golang
GolangGolang
Golang
 
Boost.Python: C++ and Python Integration
Boost.Python: C++ and Python IntegrationBoost.Python: C++ and Python Integration
Boost.Python: C++ and Python Integration
 
Go Programming Language (Golang)
Go Programming Language (Golang)Go Programming Language (Golang)
Go Programming Language (Golang)
 
Разработка кросс-платформенного кода между iPhone &lt; -> Windows с помощью o...
Разработка кросс-платформенного кода между iPhone &lt; -> Windows с помощью o...Разработка кросс-платформенного кода между iPhone &lt; -> Windows с помощью o...
Разработка кросс-платформенного кода между iPhone &lt; -> Windows с помощью o...
 
Vladymyr Bahrii Understanding polymorphism in C++ 16.11.17
Vladymyr Bahrii Understanding polymorphism in C++ 16.11.17Vladymyr Bahrii Understanding polymorphism in C++ 16.11.17
Vladymyr Bahrii Understanding polymorphism in C++ 16.11.17
 
Not Your Fathers C - C Application Development In 2016
Not Your Fathers C - C Application Development In 2016Not Your Fathers C - C Application Development In 2016
Not Your Fathers C - C Application Development In 2016
 
Basic c++ 11/14 for python programmers
Basic c++ 11/14 for python programmersBasic c++ 11/14 for python programmers
Basic c++ 11/14 for python programmers
 
Python on a chip
Python on a chipPython on a chip
Python on a chip
 

Similar to Android and cpp

Jdk 7 4-forkjoin
Jdk 7 4-forkjoinJdk 7 4-forkjoin
Jdk 7 4-forkjoin
knight1128
 

Similar to Android and cpp (20)

Android ndk
Android ndkAndroid ndk
Android ndk
 
JVM Mechanics: When Does the JVM JIT & Deoptimize?
JVM Mechanics: When Does the JVM JIT & Deoptimize?JVM Mechanics: When Does the JVM JIT & Deoptimize?
JVM Mechanics: When Does the JVM JIT & Deoptimize?
 
Using the Android Native Development Kit (NDK)
Using the Android Native Development Kit (NDK)Using the Android Native Development Kit (NDK)
Using the Android Native Development Kit (NDK)
 
Improving Java performance at JBCNConf 2015
Improving Java performance at JBCNConf 2015Improving Java performance at JBCNConf 2015
Improving Java performance at JBCNConf 2015
 
Improving Android Performance at Droidcon UK 2014
Improving Android Performance at Droidcon UK 2014Improving Android Performance at Droidcon UK 2014
Improving Android Performance at Droidcon UK 2014
 
Eric Lafortune - The Jack and Jill build system
Eric Lafortune - The Jack and Jill build systemEric Lafortune - The Jack and Jill build system
Eric Lafortune - The Jack and Jill build system
 
Silicon Valley JUG: JVM Mechanics
Silicon Valley JUG: JVM MechanicsSilicon Valley JUG: JVM Mechanics
Silicon Valley JUG: JVM Mechanics
 
[C++ Korea] Effective Modern C++ Study, Item 11 - 13
[C++ Korea] Effective Modern C++ Study, Item 11 - 13[C++ Korea] Effective Modern C++ Study, Item 11 - 13
[C++ Korea] Effective Modern C++ Study, Item 11 - 13
 
Jdk 7 4-forkjoin
Jdk 7 4-forkjoinJdk 7 4-forkjoin
Jdk 7 4-forkjoin
 
Json generation
Json generationJson generation
Json generation
 
JavaScript: The Good Parts Or: How A C# Developer Learned To Stop Worrying An...
JavaScript: The Good Parts Or: How A C# Developer Learned To Stop Worrying An...JavaScript: The Good Parts Or: How A C# Developer Learned To Stop Worrying An...
JavaScript: The Good Parts Or: How A C# Developer Learned To Stop Worrying An...
 
Construire une application JavaFX 8 avec gradle
Construire une application JavaFX 8 avec gradleConstruire une application JavaFX 8 avec gradle
Construire une application JavaFX 8 avec gradle
 
Catch a spider monkey
Catch a spider monkeyCatch a spider monkey
Catch a spider monkey
 
Invoke Dynamic
Invoke DynamicInvoke Dynamic
Invoke Dynamic
 
Lies Told By The Kotlin Compiler
Lies Told By The Kotlin CompilerLies Told By The Kotlin Compiler
Lies Told By The Kotlin Compiler
 
Shiksharth com java_topics
Shiksharth com java_topicsShiksharth com java_topics
Shiksharth com java_topics
 
Building native Android applications with Mirah and Pindah
Building native Android applications with Mirah and PindahBuilding native Android applications with Mirah and Pindah
Building native Android applications with Mirah and Pindah
 
iOS for Android Developers (with Swift)
iOS for Android Developers (with Swift)iOS for Android Developers (with Swift)
iOS for Android Developers (with Swift)
 
Introduction to clojure
Introduction to clojureIntroduction to clojure
Introduction to clojure
 
Jug trojmiasto 2014.04.24 tricky stuff in java grammar and javac
Jug trojmiasto 2014.04.24  tricky stuff in java grammar and javacJug trojmiasto 2014.04.24  tricky stuff in java grammar and javac
Jug trojmiasto 2014.04.24 tricky stuff in java grammar and javac
 

Recently uploaded

The title is not connected to what is inside
The title is not connected to what is insideThe title is not connected to what is inside
The title is not connected to what is inside
shinachiaurasa2
 
%+27788225528 love spells in Knoxville Psychic Readings, Attraction spells,Br...
%+27788225528 love spells in Knoxville Psychic Readings, Attraction spells,Br...%+27788225528 love spells in Knoxville Psychic Readings, Attraction spells,Br...
%+27788225528 love spells in Knoxville Psychic Readings, Attraction spells,Br...
masabamasaba
 
%+27788225528 love spells in Huntington Beach Psychic Readings, Attraction sp...
%+27788225528 love spells in Huntington Beach Psychic Readings, Attraction sp...%+27788225528 love spells in Huntington Beach Psychic Readings, Attraction sp...
%+27788225528 love spells in Huntington Beach Psychic Readings, Attraction sp...
masabamasaba
 
AI Mastery 201: Elevating Your Workflow with Advanced LLM Techniques
AI Mastery 201: Elevating Your Workflow with Advanced LLM TechniquesAI Mastery 201: Elevating Your Workflow with Advanced LLM Techniques
AI Mastery 201: Elevating Your Workflow with Advanced LLM Techniques
VictorSzoltysek
 
%+27788225528 love spells in new york Psychic Readings, Attraction spells,Bri...
%+27788225528 love spells in new york Psychic Readings, Attraction spells,Bri...%+27788225528 love spells in new york Psychic Readings, Attraction spells,Bri...
%+27788225528 love spells in new york Psychic Readings, Attraction spells,Bri...
masabamasaba
 

Recently uploaded (20)

%in ivory park+277-882-255-28 abortion pills for sale in ivory park
%in ivory park+277-882-255-28 abortion pills for sale in ivory park %in ivory park+277-882-255-28 abortion pills for sale in ivory park
%in ivory park+277-882-255-28 abortion pills for sale in ivory park
 
%in Midrand+277-882-255-28 abortion pills for sale in midrand
%in Midrand+277-882-255-28 abortion pills for sale in midrand%in Midrand+277-882-255-28 abortion pills for sale in midrand
%in Midrand+277-882-255-28 abortion pills for sale in midrand
 
Payment Gateway Testing Simplified_ A Step-by-Step Guide for Beginners.pdf
Payment Gateway Testing Simplified_ A Step-by-Step Guide for Beginners.pdfPayment Gateway Testing Simplified_ A Step-by-Step Guide for Beginners.pdf
Payment Gateway Testing Simplified_ A Step-by-Step Guide for Beginners.pdf
 
VTU technical seminar 8Th Sem on Scikit-learn
VTU technical seminar 8Th Sem on Scikit-learnVTU technical seminar 8Th Sem on Scikit-learn
VTU technical seminar 8Th Sem on Scikit-learn
 
The title is not connected to what is inside
The title is not connected to what is insideThe title is not connected to what is inside
The title is not connected to what is inside
 
Introducing Microsoft’s new Enterprise Work Management (EWM) Solution
Introducing Microsoft’s new Enterprise Work Management (EWM) SolutionIntroducing Microsoft’s new Enterprise Work Management (EWM) Solution
Introducing Microsoft’s new Enterprise Work Management (EWM) Solution
 
Crypto Cloud Review - How To Earn Up To $500 Per DAY Of Bitcoin 100% On AutoP...
Crypto Cloud Review - How To Earn Up To $500 Per DAY Of Bitcoin 100% On AutoP...Crypto Cloud Review - How To Earn Up To $500 Per DAY Of Bitcoin 100% On AutoP...
Crypto Cloud Review - How To Earn Up To $500 Per DAY Of Bitcoin 100% On AutoP...
 
%+27788225528 love spells in Knoxville Psychic Readings, Attraction spells,Br...
%+27788225528 love spells in Knoxville Psychic Readings, Attraction spells,Br...%+27788225528 love spells in Knoxville Psychic Readings, Attraction spells,Br...
%+27788225528 love spells in Knoxville Psychic Readings, Attraction spells,Br...
 
8257 interfacing 2 in microprocessor for btech students
8257 interfacing 2 in microprocessor for btech students8257 interfacing 2 in microprocessor for btech students
8257 interfacing 2 in microprocessor for btech students
 
Microsoft AI Transformation Partner Playbook.pdf
Microsoft AI Transformation Partner Playbook.pdfMicrosoft AI Transformation Partner Playbook.pdf
Microsoft AI Transformation Partner Playbook.pdf
 
%in Bahrain+277-882-255-28 abortion pills for sale in Bahrain
%in Bahrain+277-882-255-28 abortion pills for sale in Bahrain%in Bahrain+277-882-255-28 abortion pills for sale in Bahrain
%in Bahrain+277-882-255-28 abortion pills for sale in Bahrain
 
Harnessing ChatGPT - Elevating Productivity in Today's Agile Environment
Harnessing ChatGPT  - Elevating Productivity in Today's Agile EnvironmentHarnessing ChatGPT  - Elevating Productivity in Today's Agile Environment
Harnessing ChatGPT - Elevating Productivity in Today's Agile Environment
 
%+27788225528 love spells in Huntington Beach Psychic Readings, Attraction sp...
%+27788225528 love spells in Huntington Beach Psychic Readings, Attraction sp...%+27788225528 love spells in Huntington Beach Psychic Readings, Attraction sp...
%+27788225528 love spells in Huntington Beach Psychic Readings, Attraction sp...
 
AI Mastery 201: Elevating Your Workflow with Advanced LLM Techniques
AI Mastery 201: Elevating Your Workflow with Advanced LLM TechniquesAI Mastery 201: Elevating Your Workflow with Advanced LLM Techniques
AI Mastery 201: Elevating Your Workflow with Advanced LLM Techniques
 
%in Stilfontein+277-882-255-28 abortion pills for sale in Stilfontein
%in Stilfontein+277-882-255-28 abortion pills for sale in Stilfontein%in Stilfontein+277-882-255-28 abortion pills for sale in Stilfontein
%in Stilfontein+277-882-255-28 abortion pills for sale in Stilfontein
 
%+27788225528 love spells in new york Psychic Readings, Attraction spells,Bri...
%+27788225528 love spells in new york Psychic Readings, Attraction spells,Bri...%+27788225528 love spells in new york Psychic Readings, Attraction spells,Bri...
%+27788225528 love spells in new york Psychic Readings, Attraction spells,Bri...
 
OpenChain - The Ramifications of ISO/IEC 5230 and ISO/IEC 18974 for Legal Pro...
OpenChain - The Ramifications of ISO/IEC 5230 and ISO/IEC 18974 for Legal Pro...OpenChain - The Ramifications of ISO/IEC 5230 and ISO/IEC 18974 for Legal Pro...
OpenChain - The Ramifications of ISO/IEC 5230 and ISO/IEC 18974 for Legal Pro...
 
WSO2Con2024 - Enabling Transactional System's Exponential Growth With Simplicity
WSO2Con2024 - Enabling Transactional System's Exponential Growth With SimplicityWSO2Con2024 - Enabling Transactional System's Exponential Growth With Simplicity
WSO2Con2024 - Enabling Transactional System's Exponential Growth With Simplicity
 
Right Money Management App For Your Financial Goals
Right Money Management App For Your Financial GoalsRight Money Management App For Your Financial Goals
Right Money Management App For Your Financial Goals
 
WSO2CON 2024 - Cloud Native Middleware: Domain-Driven Design, Cell-Based Arch...
WSO2CON 2024 - Cloud Native Middleware: Domain-Driven Design, Cell-Based Arch...WSO2CON 2024 - Cloud Native Middleware: Domain-Driven Design, Cell-Based Arch...
WSO2CON 2024 - Cloud Native Middleware: Domain-Driven Design, Cell-Based Arch...
 

Android and cpp

  • 1. Android and C++ Joan Puig Sanz
  • 3. What we will see? 1. Apps for all the platforms 2. C++ 11 3. Libraries 4. Java, C++ and JNI 5. Final thoughts 3
  • 4. Text The same app running in all the platforms 4
  • 5. 5
  • 6. Most common solutions? PhoneGap Adobe Air Xamarin Titanium 6
  • 7. 7
  • 8. ✦ Not native UI ✦ Slow performance ✦ Custom components. ✦ Depend on a company ✦ Poor user experience 8
  • 9. Good user experience Smooth UI UX 9
  • 10. Text An other old solution… C++ 10
  • 11. Why C++? Cross platform language Better performance Mature language Lots of libraries 11
  • 12. Combining C++ with Android Native UI and UX JNI C++ core 12
  • 13. Text C++ 11 features 13
  • 14. C++11 Features :: Auto The compiler deducing the type auto i = 42; // i is an int auto l = 42LL; // l is an long long auto p = new Foo(); // p is a foo* std::map<std::string, std::vector<int>> map; for(auto it = begin(map); it != end(map); ++it) {} 14
  • 15. C++11 Features :: Range-based for loops Iterate collections with foreach std::vector<int> v; v.push_back(1); v.push_back(2); v.push_back(3); for (auto value : v) { std::cout << value << std::endl; } 15
  • 16. C++11 Features :: Smart pointers unique_ptr: Ownership of a memory resource it is not shared, but it can be transferred to another unique_ptr shared_ptr: Ownership of a memory resource should be shared weak_ptr: Holds a reference to an object managed by a shared_ptr, but does not contribute to the reference count; it is used to break dependency cycles. 16
  • 17. C++11 Features :: Lambdas Powerful feature borrowed from functional programming. You can use lambdas wherever a function object or a functor or a std::function is expected std::function<int(int)> lfib = [&lfib](int n) { return n < 2 ? 1 : lfib(n-1) + lfib(n-2); }; 17
  • 18. C++11 Features :: More Final and override non-member begin() and end() Initializer lists Object construction improvement Unrestricted unions User-defined literals static_assert Strongly-typed enums … 18
  • 19. Text Complementing C++ Libraries 19
  • 20. Complementing C++ C++11 standard library is missing utilities: HTTP Requests XML and JSON Big numbers Security Math 20
  • 21. C++ libs :: Boost Supports: Licence: AS IS Big community Lots of modules 21
  • 22. C++ libs :: Juce Supports: No WP (for now) Licence: Core: AS IS Other modules: GPL and commercial licence Very well written code Easy to use 22
  • 23. C++ libs :: Qt Supports: Licence: GPL and commercial licence Big community Lots of modules 23
  • 24. Text Putting stuff together JNI 24
  • 25. Calling JNI from Java Declare native methods private native void doSomethingNative (String str); Implement C method JNIEXPORT void Java_com_example_MyClass_doSomethingNative (JNIEnv *env, jobject obj, jstring s) { const char* const utf8 = env->GetStringUTFChars (s, nullptr); CharPointer_UTF8 utf8CP (utf8); String cppString (utf8CP); env->ReleaseStringUTFChars (s, utf8); // Do Something } 25
  • 26. Calling JNI from Java JNIEXPORT void Java_com_example_MyClass_doSomethingNative (JNIEnv *env, jobject obj, jstring s) Required macro to support Windows Java + package_name + className + methodName 26
  • 27. Calling C from Java JNIEXPORT void Java_com_example_MyClass_doSomethingNative (JNIEnv *env, jobject obj, jstring s) Structure to access all the JNI functions Java object that calls the native function Java method arguments 27
  • 28. Local and global references Local reference will be managed by java A global reference is managed by the developer Max number of java references = 512 28
  • 29. Calling Java from C public String myMethod (int[] array, boolean enabled) 29
  • 30. Calling Java from C public String myMethod (int[] array, boolean enabled) JNIEnv* env = getEnv(); jclass myJavaClass = env->GetObjectClass (myJavaObject); jmethodID myJavaMethod = env->GetMethodID(myJavaClass , ”methodName", "([I;Z)Ljava/lang/String"); jstring jresult = (jstring) env->CallObjectMethod (myJavaObject, myJavaMethod , myIntArray, myBoolean); // Do something env->DeleteLocalRef (jresult); env->DeleteLocalRef (myJavaClass); 30
  • 31. Calling Java from C public String myMethod (int[] array, boolean enabled) JNIEnv* env = getEnv(); jclass myJavaClass = env->GetObjectClass(myJavaObject); jmethodID myJavaMethod = env->GetMethodID(myJavaClass , ”methodName", "([I;Z)Ljava/lang/String"); jstring jresult = (jstring) env->CallObjectMethod (myJavaObject, myJavaMethod , myIntArray, myBoolean); // Do something env->DeleteLocalRef (jresult); env->DeleteLocalRef (myJavaClass); Must not be NULL This is the java object that has the method 31
  • 32. Calling Java from C public String myMethod (int[] array, boolean enabled) JNIEnv* env = getEnv(); jclass myJavaClass = env->GetObjectClass(myJavaObject); jmethodID myJavaMethod = env->GetMethodID(myJavaClass, ”myMethod", "([I;Z)Ljava/lang/String"); jstring jresult = (jstring) env->CallObjectMethod (myJavaObject, myJavaMethod , myIntArray, myBoolean); // Do something env->DeleteLocalRef Method signature (jresult); env->DeleteLocalRef (myJavaClass); 32
  • 33. Calling Java from C public String myMethod (int[] array, boolean enabled) JNIEnv* env = getEnv(); jclass myJavaClass = env->GetObjectClass(myJavaObject); jmethodID myJavaMethod = env->GetMethodID(myJavaClass, ”myMethod", "([I;Z)Ljava/lang/String"); jstring jresult = (jstring) env->CallObjectMethod (myJavaObject, myJavaMethod , myIntArray, myBoolean); // Do something env->DeleteLocalRef Method signature (jresult); env->DeleteLocalRef (myJavaClass); Type Signature Java Type Z Boolean B byte C char S short I int J long F float D double L class ; full qualified [type; tcylpases[] 33
  • 34. Calling Java from C public String myMethod (int[] array, boolean enabled) JNIEnv* env = getEnv(); jclass myJavaClass = env->GetObjectClass(myJavaObject); jmethodID myJavaMethod = env->GetMethodID(myJavaClass, ”myMethod", "([I;Z)Ljava/lang/String"); jstring jresult = (jstring) env->CallObjectMethod (myJavaObject, myJavaMethod , myIntArray, myBoolean); // Do something env->DeleteLocalRef Method signature (jresult); env->DeleteLocalRef (myJavaClass); 34
  • 35. Calling Java from C public String myMethod (int[] array, boolean enabled) JNIEnv* env = getEnv(); jclass myJavaClass = env->GetObjectClass(myJavaObject); jmethodID myJavaMethod = env->GetMethodID(myJavaClass , ”myMethod", "([I;Z)Ljava/lang/String"); jstring jresult = (jstring) env->CallObjectMethod (myJavaObject, myJavaMethod , myIntArray, myBoolean); // Do something env->DeleteLocalRef (jresult); env->DeleteLocalRef (myJavaClass); 35
  • 36. Calling Java from C public String myMethod (int[] array, boolean enabled) JNIEnv* env = getEnv(); jclass myJavaClass = env->GetObjectClass(myJavaObject); jmethodID myJavaMethod = env->GetMethodID(myJavaClass , ”myMethod", "([I;Z)Ljava/lang/String"); jstring jresult = (jstring) env->CallObjectMethod (myJavaObject, myJavaMethod , myIntArray, myBoolean); // Do something env->DeleteLocalRef (jresult); env->DeleteLocalRef (myJavaClass); 36
  • 37. Java and C++ object binding 37
  • 38. Java and C++ object binding Java (OO) C C++ (OO) 38
  • 39. Java and C++ object binding Java (OO) C C++ (OO) 39
  • 40. Foo Java implementation public class Foo { native void destroyCppInstanceNative(double ref); native long newCppInstanceNative(); native String getStringNative(double ref); private double _ref = 0; public Foo() { _ref = newCppInstanceNative(); } public String getString() { return getStringNative(_ref); } public void destroy() { destroyCppInstanceNative(_ref); } } 40
  • 41. Foo Java implementation JNIEXPORT long Java_com_example_Foo_newCppInstanceNative(JNIEnv *env, jobject obj) { Foo* newFoo = new Foo(); return (double)(newFoo); } JNIEXPORT jstring Java_com_example_Foo_getStringNative(JNIEnv *env, jobject obj, double ref) { Foo* foo = (Foo*)(ref); jstring jStringResult = env->NewStringUTF (foo->getString()); return jStringResult; } JNIEXPORT void Java_com_example_Foo_destroyCppInstanceNative(JNIEnv *env, jobject obj, double ref) { Foo* foo = (Foo*)(ref); delete foo; } 41
  • 42. Text Some advice to live happier with C++ 42
  • 43. Some advice Code quality! (Code conventions, code reviews, etc.) C++ is not a read only code, don’t put the blame on it Remember to initialise all the values in the constructor Use unity builds to speed up compilation time JNI could be painful. Check out djinni to generate cross-language type declarations and interface bindings. dropbox/djinni 43
  • 44. Final thoughts Pros Same core and with native UI/UX per platform Better performance Faster cross platform development Easier maintenance Cons Need to learn a new language Android apps will be bigger (code compiled for different architectures) Can be fixed distributing specific apk per each architecture 44