- Situation (Situation)
- Took three chapters
- 3 q
- Three see
- Look back
- To look out
- Look ahead
- Think twice before
- complacency
- Think back
- Change going
- Three wishes
- Conflict (Complication)
- Question (Question)
- 5 w2h method
- The Answer (the Answer)
- Three principles
- rational
- good
- A nodal
- Skilled and magical craftsmanship
- gird
- Make a clean break
- Swallowing knives spitting fire
- Java and JavaScript communicate directly
- Java and C++ communicate
- JavaScript and C++ communicate
- Do It
- A picture
- fishing
- fish
- The advanced
- reference
- A long song
- Cold kiln fu
- Three principles
☞Read the original
At present, I have not found any ReactNative article that enables me to achieve the proficiency of Native development. In @Hu Zhaoxu, “ReactNative involves Native(Android/iOS), C and JavaScript. Most of the industry only knows one of them, and a few of them know two. And they didn’t have time to write about it.
Here’s my chance
ReactNative involves a technology stack including front-end, client, cross-platform communication, and languages including Java/Object-C, C, and JavaScript.
Looking directly at the source code is definitely confused.
I tried to start with“Principle + Practice, learn and do now”The point of view ofHandwritten ReactNativeTo deepen understanding.
The goal is to learn how to use it and then wonder why!
Situation (Situation)
Took three chapters
- This article has not touched the source code of ReactNative yet, it is my one-sided fantasy, mixed with some jokes and long-winded three views, just for laughs.
- This article is written on the basis of the running and passing of Advance OnAct Native Demo (environment for Mac). The Native end starts from Java and does not include Object-C at present [because I am Android development, not iOS].
- This paper is one of my ideas to solve the problem. Because of my current level limitation, if there are other better solutions, PLEASE kindly advise me.
3 q
- Who I am: Android Wild App monkey focused on mobile Internet.
- Where you come from: Part of the big front end (FontEnd, iOS, Android) battle sequence, alongside the full stack (product, R&D (front end, back end), testing).
- Where to go: Full stack engineer.
Three see
Look back
- In the Age of the Internet, browsers rule the world, and most needs (chat, shopping, watching TV, information, etc.) use browsers “on the go”. Only a small amount of tool-level software is developed using Native (Word, PPT, Excel, translation dictionary, etc.).
- Mobile Internet era, most of the requirements are independent application (Meituan, mobile phones, baidu, Tmall, jingdong, headlines, etc.), but must also have a matching web version, or you can’t use WeChat share out, and the user’s phone usually come with the big MAC application, basic covers beer and skittles, so is unlikely to install other homogeneous applications, If you can’t do it, try it on the web.
- Disadvantages of downloading and installing an app: downloading takes time, wastes traffic, occupies space, affects the performance of the phone, and leaks privacy.
- The user is god, can you make God obey you?
To look out
- Facebook, the industry leader, launched ReactNative 15 years ago and is now a global phenomenon. Google launched Flutter in 2017 and it was a hit. Domestic giants such as wechat Mini program, Ali Weex, And Volkswagen Dianping Picasso. No one is not the tide of The Times.
- Client-side dynamic solution technology evolution: Web Hybrid Plug-in ReactNative, Weex, miniprogram, Fultter.
- The number of front-end users of the company has been growing rapidly in recent years. In the past, Native applications (H5, Android and iOS) were mainly implemented in the App, but now most of them are replaced by H5 (H5 and Android and iOS are equally popular). In particular, the rapid trial-and-error and timely launch of H5 make it the king of the terminal.
- With the rapid changes of Mobile Internet (H5 catches up with wave after wave without waiting for Native backup), Mobile phone hardware performance is improved, communication network is constantly upgraded, and various front-end solutions are blooming (offline, AMP (Accelerated Mobile Pages, Mobile page acceleration), PWA (Progressive Web App)), provide the material foundation for the front end to dominate the world.
Look ahead
- “Science and technology are the primary productive force.” – grandpa deng
- “Labor productivity is constantly developing with the continuous progress of science and technology.” – Marx
- In short, the emergence of dynamic solutions is not to replace anyone, but to provide better experience for users. Meanwhile, businesses can iterate faster and bring better products to users in continuous attempts. — Let’s talk about mobile mobility
- “Don’t make a fool of your times, don’t make a fool of your poverty, and let the world go round and round.” – cold kiln fu
▽ Ye Jun-sungThinking and practice of the front-end technology system of Meituan Travel
Think twice before
complacency
- Front end engineers develop applications using technologies like ReactNative and Fultter, with one front end engineer and two Android and iOS engineers.
- Companies don’t spend money on idlers (why hire two client engineers when one front-end engineer can do the job).
- JavaScript is popular, a language that can be developed across both front-end browser applications and back-end NodeJS services. Front-end engineers are rapidly evolving into full-stack engineers.
- Fully exploiting the computing power of the client side is a huge temptation to the operating cost of the company (considering that the computing power of 100 million mobile phones is on the server side, how many servers are needed, and all kinds of network transmission and load balancing problems, why not save the money?).
Think back
- Be open to change. If you’re limited to client development, you’ll get laid off sooner or later, unless you’re awesome.
- Knowing your enemy, it’s time to stop on the client side and get to know the front-end stack.
Change going
- This is an opportunity for the client to move to the big front end, the starting point for the full stack engineer.
- Moving from client engineer to front-end engineer is challenging, but the benefits are self-evident.
- The client side has an insurmountable performance advantage over the front end, and simple front-end development cannot give play to the ultimate user experience. Therefore, the world is ultimately dominated by full-stack engineers (client side, front-end, server side). Compared to front-end engineers learning client technology, the threshold for client engineers to learn front-end technology is much lower.
- Technology has always been one of the core competitiveness of engineers. — My tutor @Qiaopu
- “The world’s martial arts, no move can be broken, only fast can be broken.” — Kung Fu by Stephen Chow
- “If it is inevitable, I wish it would come sooner.” — In The Kangxi Dynasty, Kang Xi answered Duke Pei of Zhou, “What is the emperor’s mind in case Wu Sangui rebelled?”
Delta -Daming Dynasty 1566
Three wishes
- I know all about ReactNative, but I still don’t know where to start.
- Closed door: manual self-made simple version of ReactNative, in-depth analysis of industrial machine ReactNative implementation principle (driving Virtual DOM and Native communication principle), ReactNative articles, high-level components.
- Break out of the door: ReactNative is the front of a ditch, fell into, called frustration, climb out, called growth.
Conflict (Complication)
- I am focused on the mobile Internet of the north drift workers, FRONT-END work I see, but did not learn, will not do, constrained in Android client development.
- I group a large area spread ReactNative, as a veteran, I do not enter hell who into hell. Better to fight than to be caught without a fight.
- Hand-to-hand confrontation about half a month, once with their own accumulated methodology and outlook on life for many years, directly into the ReactNative source code, hard to read three times the great guo xiaoxing ReactNative source code, JavaScript, C++, Android switch back and forth, all kinds of high energy warning, hit my face dog blood, I was so disoriented and confused that I almost threw myself into the street.
- Direct debug source code, JavaScript layer code can not see, a set of one, looked for a long time did not find where the door; The Android layer has found the entry point for message communication.
- A pawn’s fate is bound to be involuntarily. “If you die now, you will die. If you make a grand plan, you will die. — The Chen Shue Family
- The most simple way, dare to face life, I began to work hard into ReactNative source code, the goal is to achieve client proficiency.
Question (Question)
5 w2h method
- What: What are the goals, What are the core issues?
- Why: What is the current state of the industry?
- Who: What are the roles, Who is the party A, Who is the party B, and Who is the beneficiary?
- -Blair: When did it happen? When did it happen?
- Where: What is the scene?
- How does this work?
- How Much is it worth? How Much is it worth?
The Answer (the Answer)
Three principles
“Rational, advantageous and restrained” are the “three principles” of war against the enemy put forward by MAO Zedong in “Strategic Problems in the Present Anti-japanese United Front”.
rational
- Value: stay true to your original aspiration, break the boundaries of client engineers, surpass yourself and strengthen core competitiveness. “Open up the waves of thousands of miles, cloth national prestige in all directions.” — Emperor Meiji
- Objective: Take ReactNative as an opportunity to evolve full-stack engineers, deeply understand the principles behind it, and expand my living space. “Design is not just about how it looks. Design is about how it works.” “– Steve Jobs
- The problem:
- Big cost: double terminal (Android and iOS) independent development, the key is the same function, can a person stem two people’s work?
- Long cycle: rely on the version (generally a monthly version, can not keep up with the wind of the mobile Internet), users need to upgrade (nothing blind upgrade, the whole bunch of chaotic functions that do not use, in addition to wasting my traffic, is to let the phone more card).
- High cost: hot repair is not mature, it is difficult to timely stop loss, good envy of the background and the front end can “secretly, quietly” the bug changed, even if the client found the problem, such as the version of the repair, then the small problem is also made all over the city. “And to prevent microcodulations, worry in not sprout.” — Biography of Wu Xi in Song Dynasty
- Fat: The layout of each app is to build an ecological platform, to create a giant app, to achieve the world. With business iteration and time, the weight of applications has skyrocketed. Make me lose weight? Kidding! Do you know how much I pay for this body?
- Approach: MECE analysis (Mad Exclusive, Collectively Exhaustive) Consider all the possibilities. Let’s say I take a pig knife and make a simple version of ReactNative by hand, pretending to be my cook.
good
- Time: Understanding the underlying principles of ReactNative can help you finish work faster and better, saving time. Are you overwhelmed by the ReactNative red screen? Can’t go deep into a problem, have to superficial another solution try? With too little information online to know what’s going on and why, you can’t do what you want?
- Raise your salary: No pain, no gain.
- Get a promotion: The company will treat you well.
- Confidence: look, XXX brother really is not cover; I feel LIKE I can handle XXX.
- Honors: 🐂🐝, 💯, 👏, 🐝,
A nodal
- Stand on the shoulders of giants and do not repeat the wheel.
- The battle line should not be too long, tomorrow you will be easy to do, do now may be a little difficult, after all, we are still growing, and tomorrow.
- Take it easy. Your energy is limited.
Skilled and magical craftsmanship
gird
- Mimicking the concept of Minimum Viable Product (MVP), a diagonal game AI program was handmade. JSX controlled the AI algorithm and UI, and a Java console output game charts and game interactions.
“Things are a chessboard, and men are pawns. You don’t know who uses who these days!” Li Keyong (Painting Rivers and Lakes
Make a clean break
- Software = logic (logic processing engine, such as JavaScriptCore) + interface (rendering engine, such as WebCore). The interface is a static image (like a comic strip) that is dynamically projected (like an animated cartoon) through logical manipulation of interface elements.
- The logic processing engine follows the user input for logic processing and outputs interface description text to the rendering engine.
- The rendering engine parses the interface description text (Html, JSX, layout code, etc.) and image resources, calls the system graphics API (OpenGL, etc.) and refreshes the interface.
Swallowing knives spitting fire
- The JavaScript code in ReactNative processes the logic and generates the interface description text to Native. Native parses it into an interface object according to the interface description text protocol and calls the graphical API to refresh the interface.
- How does Java run JavaScript?
Java and JavaScript communicate directly
☞ Search the Internet for a Demo, take the principle {:.info}
- Java can learn JavaScript code directly through ScriptEngine calls.
- Refer to Java and JS communication, Java ScriptEngine use to implement Java to run JS code helloScriptengin.java
-
The core code is shown below (see HelloScriptenine.java for the complete code)
public void testJSCore2() {// Initialize JS script engine ScriptEngineManager Factory = new ScriptEngineManager(); ScriptEngine engine = factory.getEngineByName("JavaScript"); // Add global variables, a = 4, b = 6 engine.put("a", 4); engine.put("b", 6); Max_num (a,b); max_num = engine.eval(a,b);"function max_num(a,b){return (a>b)? a:b; }max_num(a,b);"); System.out.println("max_num:"+ maxNum); } catch (Exception e) { e.printStackTrace(); }} // Run the command line: shengshuqiangdeMacBook-Pro:java shengshuqiang$ javac HelloScriptEngine.java shengshuqiangdeMacBook-Pro:java Shengshuqiang $Java HelloScriptEngine hello,SSU 2./hello.js hello js 19 handleMsg: I subscribe to SSU, a fantastic 💯, a fantastic 💯 max_num:6Copy the code
I wanted to simplify a bit and avoid the C++ layer. However, dual-terminal communication and shared context cannot be realized, but (▔, ▔)ㄏ does not pass through the system, so we can only go back to the starting point. Just Do C++!
Java and C++ communicate
☞JNI (JAVA Native Interface) : JAVA Native Interface, a protocol that provides a programming framework for JAVA and Native languages (C/C++) to call each other.
- Run through the first Java and C++ call example hellojni.java through JNI exploration.
-
The core code example is as follows (see Hellojni.java for the complete code)
// HelloJNI.java public class HelloJNI { static { System.loadLibrary("NativeLibrary"); } public static native void sendMsg(String msg); public static void main(String[] args) { System.out.println("Hello SSU!"); sendMsg("SSU"); } } // HelloJNI.cpp JNIEXPORT void JNICALL Java_HelloJNI_sendMsg(JNIEnv * env, jclass cls, jstring jstr) { const char* str = env->GetStringUTFChars(jstr, NULL); printf("Java_HelloJNI_sendMsg:%s\n", str); env->ReleaseStringUTFChars(jstr, str); } // Run the command line: shengshuqiangdeMacBook-Pro:java shengshuqiang$ javac HelloJNI.java shengshuqiangdeMacBook-Pro:java shengshuqiang$ javah HelloJNI shengshuqiangdeMacBook-Pro:java shengshuqiang$ gcc -dynamiclib HelloJNI.cpp -o libNativeLibrary.jnilib -I ./include/ shengshuqiangdeMacBook-Pro:java shengshuqiang$ java HelloJNI Hello SSU! Java_HelloJNI_sendMsg:SSUCopy the code
JNI advanced
- The JNI specification
- JNI specification companion code Example JNI Example
▽ Old farm horseThe JNI specification
JavaScript and C++ communicate
☞JS engineJSCore and V8, I choose.
- V8 source code, of course, I do not understand.
- First look for a few articles to learn, know
- Develop customizable applications using the Google V8 engine
- Getting to know the V8 engine
- Shallow read V8 – powerful JavaScript engine
- Introduction to the use of V8 engine in C++ programs
- Here, I fell into a pit inside, is trying to compile V8 source code, found gClient simply can’t download down, once shed tears ┭┮﹏┭┮
- After a bit of pestering, I did a quick github search for working V8Demo code.
- Only the truth in the world, also really find me an available depend on the V8 dynamic library running JS code coderzh/V8 – demo, there is a direct reference compiled V8 dynamic link library libv8. Dylib, libv8_libplatform. Dylib.
- It was the first step in my journey. It uses CMake and Make to compile and run code, which I used for the first time.
Cc {// Initialize context v8::Isolate::Scope isolate_scope(Isolate); v8::HandleScope handle_scope(isolate); v8::Local<v8::Context> context = v8::Context::New(isolate); v8::Context::Scope context_scope(context); // Pass in simple JS string concatenation code"Hello, World!"
v8::Local<v8::String> source = v8::String::NewFromUtf8(isolate, "'Hello' + ', World! '", v8::NewStringType::kNormal).ToLocalChecked();
// Compile the source code.
v8::Local<v8::Script> script = v8::Script::Compile(context, source).ToLocalChecked();
// Run the script to get the result.
v8::Local<v8::Value> result = script->Run(context).ToLocalChecked();
// Convert the result to an UTF8 string and print it.
v8::String::Utf8Value utf8(isolate, result);
printf("%s\n", *utf8); Dyld: Library not loaded: /usr/localLibv8.dylib ", can not find v8 dynamic link library // the solution is to copy the libs dynamic link library file directly to /usr/local/lib (cp.. /libs/* /usr/local/lib) 。
shengshuqiangdeMacBook-Pro:AdvanceOnReactNative shengshuqiang$ mkdir build
shengshuqiangdeMacBook-Pro:AdvanceOnReactNative shengshuqiang$ cdbuild/ shengshuqiangdeMacBook-Pro:build shengshuqiang$ cmake .. The C compiler Identification is AppleClang 10.0.0.10001145 The CXX compiler Identification is AppleClang 10.0.0.10001145 - Checkfor working C compiler: /Applications/Xcode.app/Contents/Developer/Toolchains/XcodeDefault.xctoolchain/usr/bin/cc
-- Check for working C compiler: /Applications/Xcode.app/Contents/Developer/Toolchains/XcodeDefault.xctoolchain/usr/bin/cc -- works
-- Detecting C compiler ABI info
-- Detecting C compiler ABI info - done
-- Detecting C compile features
-- Detecting C compile features - done
-- Check for working CXX compiler: /Applications/Xcode.app/Contents/Developer/Toolchains/XcodeDefault.xctoolchain/usr/bin/c++
-- Check for working CXX compiler: /Applications/Xcode.app/Contents/Developer/Toolchains/XcodeDefault.xctoolchain/usr/bin/c++ -- works
-- Detecting CXX compiler ABI info
-- Detecting CXX compiler ABI info - done
-- Detecting CXX compile features
-- Detecting CXX compile features - done
-- Configuring done
-- Generating done
-- Build files have been written to: /Users/shengshuqiang/ideal/HelloJSCore/AdvanceOnReactNative/build
shengshuqiangdeMacBook-Pro:build shengshuqiang$ make
Scanning dependencies of target v8_demo
[ 50%] Building CXX object CMakeFiles/v8_demo.dir/src/main.cc.o
[100%] Linking CXX executable v8_demo
[100%] Built target v8_demo
shengshuqiangdeMacBook-Pro:build shengshuqiang$ ./v8_demo
dyld: Library not loaded: /usr/local/lib/libv8.dylib
Referenced from: /Users/shengshuqiang/ideal/HelloJSCore/AdvanceOnReactNative/build/./v8_demo
Reason: image not found
Abort trap: 6 shengshuqiangdeMacBook-Pro:build shengshuqiang$ cp .. /libs/* /usr/local/lib shengshuqiangdemacbook-pro: Build shengshuqiang$./v8_demoCopy the code
- Coderzh/V8-Demo can only run simple JS string concatenation code, and although there is a light at the end of the tunnel, it is far from sunrise.
- Once again, blessed by fortune,Embed V8 core conceptsandEmbed the core concept of V8 1It got me throughThere are three examples in the V8 source codeCc, process.cc, shell.cc), this is a critical step forward, this is a milestone.
- Hello-world. cc: simply print “Hello world”.
- Process. cc: demonstrates how C++ calls JavaScript functions.
- Shell. cc: demonstrates how to expose native functions to JavaScript.
// hello.js // diagonal chess program // initialization, mainly configure the output character of the board game init = () => {RedArmy ='🔥'
BlackArmy = '💧'
EmptyArmy = '🎄'
Board = [EmptyArmy, BlackArmy, BlackArmy, BlackArmy, EmptyArmy, EmptyArmy, EmptyArmy, RedArmy, RedArmy, RedArmy]
Location = ['attending'.'①'.'2.'.'3.'.'④'.'⑤'.'⑥'.'⑦'.'today'.'pet-name ruby']
Left2Right = '一'
Top2Bottom = '|'
LeftBottom2RightTop = '╱'
LeftTop2RightBottom = '╲'
Space = '\t'
stepIndex = 0
printBoard()
printMsg("Please 🌴 🐑"); } // buildChess character buildChess = index => (Location[index] + Board[index]) // print checkerboard charactersprintBoard = () => {
let str = buildChess(1) + Space + Left2Right + Space + buildChess(2) + Space + Left2Right + Space + buildChess(3) + '\n'
+ Top2Bottom + Space + LeftTop2RightBottom + Space + Top2Bottom + Space + LeftBottom2RightTop + Space + Top2Bottom + '\n'
+ buildChess(4) + Space+ Left2Right + Space + buildChess(5) + Space + Left2Right + Space + buildChess(6) + '\n'
+ Top2Bottom + Space + LeftBottom2RightTop + Space + Top2Bottom + Space + LeftTop2RightBottom + Space + Top2Bottom + '\n'
+ buildChess(7) + Space + Left2Right + Space + buildChess(8) + Space + Left2Right + Space + buildChess(9) + '\n'
printMsg(STR)} // print interface, since console.log cannot be used directly in V8, C++ print function is called hereprint
printMsg = msg => {
// console.log(msg)
printReceiveOrderStr = orderStr => {receiveOrderStr = orderStr => {if(orderStr && orderStr.length == 2) { const srcIndex = parseInt(orderStr.charAt(0)) const destIndex = ParseInt (orderstr.charat (1)) // Check the validity of input instructionif (srcIndex >= 1 && srcIndex <= 9 && destIndex >= 1 && destIndex <= 9) {
handleOrder(srcIndex, destIndex)
} else {
printMsg('🈲🚫 foul ⛔️ input command ['+ orderStr + '] error, should be two digits 1-9, source position destination position ')}}else {
printMsg('🈲🚫 foul ⛔️ input command ['+ orderStr + '] error, should be two digits 1-9, source position destination position 'HandleOrder = (srcIndex, destIndex) =>printMsg('handleOrder Source Location ' + srcIndex + 'pieces' + Board[srcIndex] + 'Move to target position' + destIndex + 'pieces'+ Board[destIndex]) // The destination location is emptyif(Board[destIndex] === EmptyArmy) {const army = (stepIndex % 2 === 0? BlackArmy : RedArmy)if (Board[srcIndex] === army) {
Board[destIndex] = army
Board[srcIndex] = EmptyArmy
printMsg('Step' + (stepIndex++) + ':' + srcIndex + '➡ ️' + destIndex)
} else {
printMsg('🈲🚫 foul ⛔️ source location ' + srcIndex + 'Not your piece.' + Board[srcIndex])
}
} else {
printMsg('🈲🚫 foul ⛔️ target location ' + destIndex + 'Existing pieces' + Board[destIndex])
}
printBoard()
}
shengshuqiangdeMacBook-Pro:c shengshuqiang$ mkdir build
shengshuqiangdeMacBook-Pro:c shengshuqiang$ cdbuild shengshuqiangdeMacBook-Pro:build shengshuqiang$ cmake .. The C compiler Identification is AppleClang 10.0.0.10001145 The CXX compiler Identification is AppleClang 10.0.0.10001145 - Checkfor working C compiler: /Applications/Xcode.app/Contents/Developer/Toolchains/XcodeDefault.xctoolchain/usr/bin/cc
-- Check for working C compiler: /Applications/Xcode.app/Contents/Developer/Toolchains/XcodeDefault.xctoolchain/usr/bin/cc -- works
-- Detecting C compiler ABI info
-- Detecting C compiler ABI info - done
-- Detecting C compile features
-- Detecting C compile features - done
-- Check for working CXX compiler: /Applications/Xcode.app/Contents/Developer/Toolchains/XcodeDefault.xctoolchain/usr/bin/c++
-- Check for working CXX compiler: /Applications/Xcode.app/Contents/Developer/Toolchains/XcodeDefault.xctoolchain/usr/bin/c++ -- works
-- Detecting CXX compiler ABI info
-- Detecting CXX compiler ABI info - done
-- Detecting CXX compile features
-- Detecting CXX compile features - done
-- Configuring done
-- Generating done
-- Build files have been written to: /Users/shengshuqiang/ideal/HelloJSCore/AdvanceOnReactNative/learn/c/build
shengshuqiangdeMacBook-Pro:build shengshuqiang$ make
Scanning dependencies of target learn
[ 50%] Building CXX object CMakeFiles/learn.dir/shell.cc.o
[100%] Linking CXX executable learn
ld: warning: directory not found for option '-L/Users/shengshuqiang/ideal/HelloJSCore/AdvanceOnReactNative/learn/c/libs'
[100%] Built target learn
shengshuqiangdeMacBook-Pro:build shengshuqiang$ ./learn
> load('.. /.. /js/hello.js') > init () (1) a (2) a (3) 💧 💧 💧 | ╲ | ╱ | (4) a 🎄 (5 🎄 a 6 🎄 | ╱ | ╲ | 7) 🔥 a 🔥 a pet-name ruby 🔥 please 🌴 🐑 > handleOrder (1, 5) HandleOrder source position 1 piece 💧 5 pieces to the target position 🎄 Step0:1 ➡ ️ 5 (1) a (2) a (3) 💧 💧 🎄 | ╲ | ╱ | (4) a 🎄 (5 💧 a 6 🎄 | ╱ | ╲ | 7) 🔥 a 🔥 a pet-name ruby 🔥 > quit ()Copy the code
Do It
☞ Thread: Java side starts JS to initialize the running environment 2. The JS side outputs game rules and chess games and waits for input from the Java side 3. The Java side injects instructions, js refreshes the board and plays chess until the decision is made 4
V8 hellojni. cc is a dynamic link library that CMake uses because CMake and CMake do not understand. At the darkest moment of my attack on ReactNative, it was @Luo Jani Goddess, @Lei Earth and @Zhang Qianyi daniu who guided me to the next level. Thank you for your help
- All that’s left is a little time and three keys: Ctrl, C, V
-
We successfully built a simple version of Handwritten ReactNative. Although React does not exist, it has developed cross-platform interaction capabilities.
// HelloJNI.java public class HelloJNI { private Scanner scanner = new Scanner(System.in); static { System.loadLibrary("HelloJNI"); } public HelloJNI() { scanner.useDelimiter(System.getProperty("line.separator")); } public native void load(String jsBundle); public native void sendOrder(String orderStr); public static void receiveMsg(String msg) { System.out.println("receiveMsg:\t" + msg); } public static void main(String[] args) { System.out.println("Hello SSU!"); HelloJNI helloJni = new HelloJNI(); String jsBundle = null; try { jsBundle = readFile(".. /hello.js"); } catch(IOException exception) { } if(null ! = jsBundle) { helloJni.load(jsBundle); }} /** * Reads data from files through character streams * @throws IOException */ public static StringreadFile(String path) throws IOException{// Separator is a separator that specifies the absolute path. TXT File File = new File(path) in the root directory of drive D. // Create a file if it does not existif(! file.exists()) { file.createNewFile(); } InputStream inputStream = new FileInputStream(file); Byte [] bs = new byte[(int)file.length()]; byte[] bs = new byte[(int)file.length()]; //readThe inputStream.read(bs) method can read only one byte at a time; inputStream.close(); String fileStr = new String(bs); // System.out.println("##JAVA##\n" + fileStr); return fileStr; } public String waitForInputOrder() { if (scanner.hasNext()) { String order = scanner.next(); // System.out.println("##JAVA##\n" + "waitForInputOrder:\t" + order); return order; } returnnull; }} // hellojni. cc void Init(JNIEnv* env, jobject jobj, const char* STR)"hello"; int argc = 1; v8::V8::InitializeICUDefaultLocation(argv); v8::V8::InitializeExternalStartupData(argv); std::unique_ptr<v8::Platform> platform = v8::platform::NewDefaultPlatform(); platform = v8::platform::NewDefaultPlatform(); v8::V8::InitializePlatform(platform.get()); v8::V8::Initialize(); v8::V8::SetFlagsFromCommandLine(&argc, &argv, true); v8::Isolate* isolate; v8::Isolate::CreateParams create_params; create_params.array_buffer_allocator = v8::ArrayBuffer::Allocator::NewDefaultAllocator(); isolate = v8::Isolate::New(create_params); {// Initialize js context v8::Isolate::Scope isolate_scope(Isolate); v8::HandleScope handle_scope(isolate); Context = CreateShellContext(ISOLATE);if (context.IsEmpty()) { fprintf(stderr, "Error creating context\n"); return; } / /printf("##C##\nInit:isolate=%p\n",isolate); ExecuteString(isolate, str); ExecuteString(isolate, "init()"); static const int kBufferSize = 256; // Enter the execution environment before evaluating any code. v8::Context::Scope context_scope(context); v8::Local<v8::String> name(v8::String::NewFromUtf8(isolate, "(shell)", v8::NewStringType::kNormal).ToLocalChecked()); while (true) { jclass cls = env->GetObjectClass(jobj); jmethodID mid = env->GetMethodID(cls, "waitForInputOrder"."()Ljava/lang/String;"); if (mid == NULL) { return; } jstring jstr = static_cast<jstring>(env->CallObjectMethod(jobj, mid)); const char* iputOrder = env->GetStringUTFChars(jstr, NULL); // printf("##C##\nJava_HelloJNI_load:iputOrder= %s\n", iputOrder); ExecuteString(isolate, iputOrder); Dispose(); Dispose(); v8::V8::Dispose(); v8::V8::ShutdownPlatform(); delete create_params.array_buffer_allocator; } shengshuqiangdeMacBook-Pro:do shengshuqiang$ pwd /Users/shengshuqiang/ideal/HelloJSCore/AdvanceOnReactNative/do shengshuqiangdeMacBook-Pro:do shengshuqiang$ mkdir build shengshuqiangdeMacBook-Pro:do shengshuqiang$ cdbuild shengshuqiangdeMacBook-Pro:build shengshuqiang$ cmake .. The C compiler Identification is AppleClang 10.0.0.10001145 The CXX compiler Identification is AppleClang 10.0.0.10001145 - Checkfor working C compiler: /Applications/Xcode.app/Contents/Developer/Toolchains/XcodeDefault.xctoolchain/usr/bin/cc -- Check for working C compiler: /Applications/Xcode.app/Contents/Developer/Toolchains/XcodeDefault.xctoolchain/usr/bin/cc -- works -- Detecting C compiler ABI info -- Detecting C compiler ABI info - done -- Detecting C compile features -- Detecting C compile features - done -- Check for working CXX compiler: /Applications/Xcode.app/Contents/Developer/Toolchains/XcodeDefault.xctoolchain/usr/bin/c++ -- Check for working CXX compiler: /Applications/Xcode.app/Contents/Developer/Toolchains/XcodeDefault.xctoolchain/usr/bin/c++ -- works -- Detecting CXX compiler ABI info -- Detecting CXX compiler ABI info - done -- Detecting CXX compile features -- Detecting CXX compile features - done -- Configuring done CMake Warning (dev): Policy CMP0042 is not set: MACOSX_RPATH is enabled by default. Run "cmake --help-policy CMP0042" for policy details. Use the cmake_policy command to set the policy and suppress this warning. MACOSX_RPATH is not specified for the following targets: HelloJNI This warning is for project developers. Use -Wno-dev to suppress it. -- Generating done -- Build files have been written to: /Users/shengshuqiang/ideal/HelloJSCore/AdvanceOnReactNative/do/build shengshuqiangdeMacBook-Pro:build shengshuqiang$ make Scanning dependencies of target HelloJNI [ 50%] Building CXX object CMakeFiles/HelloJNI.dir/HelloJNI.cc.o In file included from /Users/shengshuqiang/ideal/HelloJSCore/AdvanceOnReactNative/do/HelloJNI.cc:1: /Users/shengshuqiang/ideal/HelloJSCore/AdvanceOnReactNative/do/HelloJNI.h:19:24: warning: 'CreateShellContext' has C-linkage specified, but returns user-defined type 'v8::Local<v8::Context>' which is incompatible with C [-Wreturn-type-c-linkage] v8::Local<v8::Context> CreateShellContext(v8::Isolate* isolate); ^ /Users/shengshuqiang/ideal/HelloJSCore/AdvanceOnReactNative/do/HelloJNI.cc:20:18: warning: ISO C++11 does not allow conversion from string literal to 'char *' [-Wwritable-strings] char* argv = "hello"; ^ 2 warnings generated. [100%] Linking CXX shared library libHelloJNI.dylib ld: warning: directory not found for option '-L/Users/shengshuqiang/ideal/HelloJSCore/AdvanceOnReactNative/do/libs'[100%] Built target HelloJNI shengshuqiangdeMacBook-Pro:build shengshuqiang$ javac .. /HelloJNI.java-d. shengshuqiangdeMacBook-Pro:build shengshuqiang$ java HelloJNI Hello SSU! ①♠︎ a ②♠︎ a ③ instituted | ♠ | | ④♢ A ⑤♢ A ⑥♢ | / | | | ⑦♤ 一 ⑧♤ 一 ⑨♤ please ♢ Order(1,5) 1➡️5 ① ①♢ one ②♠︎ one ③♠ medicine | | / | ④♢ one ⑤ police - ⑥♢ | | | | ⑦♤ one ⑧♤ one ⑨♤ handleOrder(7,4) 7➡️4 ① ①♢ a ②♠︎ a ③♠ papa | | / | ④ ➡️ a ⑤ ➡️ a ⑥♢ | | / | ╲ | ⑦ ⑧♤ 一 ⑨♤ quit() shengshuqiangdemacbook-pro :build shengshuqiang$Copy the code
A picture
fishing
- Read a technical article every day and post it on moments. I’ll throw a brick first: Attack ReactNative- Nabakawa
- Just Do It.
fish
- Run cross-platform (Java, C, JavaScript) Demo AdvanceOnReactNative
- Some good reasons for drifting north
The advanced
- Attack ReactNative- Nabaekawa
reference
- In-depth understanding of JSCore
- Guo Xiaoxing ReactNative source code
- Let’s talk about mobile dynamic solutions
- Thinking and practice of the front-end technology system of Meituan Travel
- Every architect should study Conway’s Law
- Java a ScriptEngine use
- Execute JS code in Java
- How do I call JS methods in Java
- JavaScriptCore Parsing (part 1)
- JavaScriptCore Parsing (part 2)
A long song
Cold kiln fu
Lu Mengzheng, a minister of the Northern Song Dynasty
It is the unforeseen that always happens. Centipede foot, line than snake; Two wings of a cock fly but not a crow. The horse has a thousand miles to travel, without riding can not go; If a man has the will to soar to the sky, he cannot pass through it without luck.
Cover wen: a person living, wealth can not be erotic, poverty and base can not move. The article, Confucius to Chen Bang; Wu slightly superior, Tai Gong fishing yu Weishui. Yan Yuan had a short life and was not a fierce man; Robber zhi is old, is not a good generation. Yao Di Ming Saint, but born unworthy son; Gusou foolish, anti – born son of filial piety. Zhang Liang was cloth yi, Xiao he called county officials. Yan Zi was appointed prime Minister of The State of Qi. Kong Ming lived in a thatched cottage and was able to serve as a strategist of Shu Han. Although the Ruler of Chu was male, he was defeated by wujiang Suicide; Although the King of Han is weak, he has thousands of miles of land. Li Guang had the power to shoot a tiger, and had no seal until he was old. Feng Tang has the talent to ride the dragon, which is rare in his life. When Han Xin did not meet him, he had to eat three meals a day. However, when he did meet han Xin, he had a jade seal hanging on his waist. Once he failed, he died at the hands of Yin people.
Some are poor before they are rich, some are old and strong, and few are old. Full of articles, white hair should not; Untalented, young and enroll. Deep hospital palace, transport back for prostitute concubine; A dissolute whore, a lady in time.
Young beauties, but for foolish husbands; A handsome man is better suited to a coarse and ugly woman. Jiaolong did not meet, diving between fish and turtles; A gentleman loses his time and hands it to a villain. Though clothes are worn, they are always presentable; With sorrow on the face, every embrace of peace. When not met, only should be safe poor keep share; If the heart does not bully, it must hold its head high. The beginning of the poor gentleman, natural bone generation; A man who is rich does not shake off cold.
When the day is not, the sun and the moon have no light; The land is not timely, vegetation is not born; Water can not, rough; When a man is out of time, good luck is out of luck. Note fortune note lu, life has been arranged, wealth who do not want? Can a man be your minister if he does not follow the rules of his foundation?
Once upon a time, I lived in Luoyang, where I begged for a monk’s meal. At night, I slept in a ruined cellar. I thought that clothes could not cover my body, and food could not help my hunger. This house toward the hall, the official to the best, the position of three public, although the body bow under one person, and the column on the ten million people, there are tart 100 liao’s rod, there are cut stingy sword, think of clothes and luo Jin thousand boxes, think of food and delicacies, out of the strong man whip, into the beauty holding the corvee, people pet, people hold. Humanity is my precious, not my ability, this is also time, also, also fate.
Jie shout! Life in the world, wealth can not be used, poverty can not deceive themselves, let the world cycle, cycle how.