1605160966

# Diving into NumPy - An Important Library Required for Data Science

NumPy, one of the most important and basic libraries used in data science and machine learning, It consists of functionalities for multidimensional arrays, high-level mathematical functions such as,

• Linear algebra operations
• Fourier transform
• Random generators

and also NumPy array forms the fundamental data structure for scikit-learn. The core of NumPy is well optimized C-code, so the execution speed is increased in Python while using Numpy.

The fundamental package for scientific computing with Python — NumPy

This article consists of the basic operations and most commonly and frequently used operations in NumPy. The article would be beginner-friendly and also act as a refresher for intermediate and advanced.

Let’s start with NumPy by importing it,

``````import numpy as np
``````

The `as` keyword makes `np` as the alias name of NumPy, so we could use np instead of NumPy. This is a common practice that saves time and makes it easier to work.

## NumPy Arrays

For creating a NumPy array we could use the`np.array` function to create it and `dtype` as an optional argument that changes the array to the required type. Here is a list of array data types. When the elements in the array are of different array data types, then the elements will be upcasted to the highest level type. This means that if an array input has mixed `int` and `float` elements, all the integers will be cast to their floating-point equivalents. If an array is mixed with `int`, `float`, and `string` elements, everything is cast to strings.

To cast an array to the required type we could use the`astype` function. The function’s required argument is the new type of array and to know the type of array we could use `.dtype`

``````#Using arange function
arr = np.arange(5)
print(arr)
#Output: [0 1 2 3 4]
arr = np.arange(2,8,2)
print(arr)
#Output: [2,4,6]

#Playing with shape and reshape
arr1 = np.arange(6)
print(arr1.shape)
#Output: (6,)
arr2 = np.reshape(arr1,(2,3))
print(arr2)
print("The shape of arr2 is',arr2.shape)
#Output: [[0 1 2]
##         [3 4 5]]
##         The shape of arr2 is (2, 3)
arr3 = np.reshape(arr2,(-1,3,2))
print(arr3)
print("The shape of arr3 is',arr3.shape)
#Output: [[[0 1]
##          [2 3]
##          [4 5]]]
##        The shape of arr3 is (1, 3, 2)

#Flattening an array
print(arr3.flatten())
#Output: [0 1 2 3 4 5]
``````

To copy an array we could use the inherent `copy` function and perform it. The NaN (Not a Number) value could also be used by using `np.nan` . The _nan _would act as a placeholder and will not take the _integer value. _If integer type is used while containing nan, it would result in an error.

## NumPy Basics

NumPy provides an option to create ranged data arrays using np.arange. The function acts very similarly to the `range` function in Python and returns a 1D array. If a single number `n` is passed as an argument then it would return numbers ranging from `0` to `n-1`. If two numbers are passed as argument `m`and `n`it would return numbers ranging from `m`to `n-1` . If three arguments are used `m`, `n` and `s` it will return numbers ranging from `m`to `n-1` using step size `s` .

The `shape` function is used to know the shape of the array. While using `reshape` function it takes input array and new shape as the arguments. For example, if the number of elements in an array is 10 then the new shape should be (5,2) or (2,5) as they form the multiplicative result. We are allowed to use the special value of -1 in at most one dimension of the new shape. The dimension with -1 will take on the value necessary to allow the new shape to contain all the elements of the array.

The `flatten` function would reshape an array of any size into a 1D array.

``````#Using arange function
arr = np.arange(5)
print(arr)
#Output: [0 1 2 3 4]
arr = np.arange(2,8,2)
print(arr)
#Output: [2,4,6]

#Playing with shape and reshape
arr1 = np.arange(6)
print(arr1.shape)
#Output: (6,)
arr2 = np.reshape(arr1,(2,3))
print(arr2)
print("The shape of arr2 is',arr2.shape)
#Output: [[0 1 2]
##         [3 4 5]]
##         The shape of arr2 is (2, 3)
arr3 = np.reshape(arr2,(-1,3,2))
print(arr3)
print("The shape of arr3 is',arr3.shape)
#Output: [[[0 1]
##          [2 3]
##          [4 5]]]
##        The shape of arr3 is (1, 3, 2)

#Flattening an array
print(arr3.flatten())
#Output: [0 1 2 3 4 5]
``````

## Math Operations

With the help of NumPy arrays, we can apply arithmetic, logical and other operations to each element in the array. This helps to modify a large amount of numeric data with only a few operations. NumPy arrays perform a basic arithmetic operation to every element in an array. Apart from the basic arithmetic function, NumPy can perform other trigonometric, hyperbolic, exponents, logarithms, and a lot more functions. These functions have been listed here.

``````arr1 = np.array([[3,4],[5,6]])
arr2 = np.array([[1,2],[3,4]])
print(arr1+2)
#Output: [[5 6]
##         [7 8]]

#Performing power operation
print(arr1**2)
#Output: [[ 9 16]
##         [25 36]]

#Performing subtraction between two array
print(arr1-arr2)
#Output: [[2 2]
##         [2 2]]

#Performing basic multiplication
print(arr1*arr2)
#Output: [[ 3  8]
##         [15 24]]

#Performing exponential function
print(np.exp(arr1))
#Output: [[ 20.08553692  54.59815003]
##         [148.4131591  403.42879349]]

#Performing logarthimic function with base 10
arr3 = np.array([[10,100],[np.e,np.pi]])
print(np.log10(arr3))
#Output: [[1\.         2\.        ]
##         [0.43429448 0.49714987]]

#Raising 3 to power of each element in array
print(np.power(3,arr2))
#Output: [[ 3  9]
##         [27 81]]

#Performing matrix multiplication
print(np.matmul(arr1,arr2))
#Output:  [[15 22]
##          [23 34]]
``````

The function np.exp `performs a _base e exponential_ on an array and` np.log10 `performs logarithms on input array using _base 10_ . To do a regular power operation with any base, we use` np.power . The first argument to the function is the base , while the second is the power . To perform matrix multiplication between two arrays we use `np.matmul` the function. The dimension of two input matrix in `np.matmul` must obey the principle of matrix multiplication . The second dimension of the first matrix must equal the first dimension of the second matrix, otherwise `np.matmul` will result in a `ValueError` .

#machine-learning #numpy #python #data-science #developer

1656984600

## 1.新建一个react native app，打开你的终端运行

``npx react-native init NativeModules``

## 3. 在 C++ 端工作

``````#ifndef Cpp_to_RN_hpp
#define Cpp_to_RN_hpp#include <stdio.h>
#include <string>class Cpp_to_RN {
public:
std::string sayHello();
};#endif /* Cpp_to_RN_hpp */``````

``````#include "Cpp_to_RN.hpp"
std::string Cpp_to_RN::sayHello(){
return "Hello from CPP";
}``````

## 4. 处理包装 C++ 文件。

``````#import <Foundation/Foundation.h>
#import "WrapCpp_to_RN.h"
#import "Cpp_to_RN.hpp"@implementation WrapCpp_to_RN- (NSString *) sayHello {
Cpp_to_RN fromCPP;
std::string helloWorldMessage = fromCPP.sayHello();
return [NSString
stringWithCString:helloWorldMessage.c_str()
encoding:NSUTF8StringEncoding];
}
@end``````

C。创建头文件并命名`WrapCpp_to_RN.h`

``````#import <Foundation/Foundation.h>
@interface WrapCpp_to_RN : NSObject
- (NSString *) wrapSayHello;
@end``````

## 5. 在 iOS (Swift) 端工作

``````#import <Foundation/Foundation.h>
@interface WrapCpp_to_RN : NSObject
- (NSString *) wrapSayHello;
@end``````

``````#import <Foundation/Foundation.h>
@interface WrapCpp_to_RN : NSObject
- (NSString *) wrapSayHello;
@end``````

``````import Foundation@objc(SendCpp_to_RN)
class SendCpp_to_RN : NSObject {

@objc static func requiresMainQueueSetup() -> Bool {
return false
}

@objc func fromCpp(_ successCallback: RCTResponseSenderBlock) -> Void {
successCallback([NSNull(), WrapCpp_to_RN().wrapSayHello() as Any])
}}``````

``````#import <React/RCTBridgeModule.h>
#import <Foundation/Foundation.h>
#import "UIKit/UIKit.h"
@interface RCT_EXTERN_MODULE(SendCpp_to_RN, NSObject)RCT_EXTERN_METHOD(fromCpp:(RCTResponseSenderBlock)successCallback)@end``````

C。将 Swift 连接到 React Native，打开`NativeModules-Bridging-Header.h` 文件

``#import <React/RCTBridgeModule.h>#import <React/RCTViewManager.h>#import "WrapCpp_to_RN.h"``

## 6. 在 React Native 方面工作

``````import React from 'react';
import {StyleSheet, Text, View, NativeModules, Button} from 'react-native';const App = () => {
const onPress = () => {
const {SendCpp_to_RN} = NativeModules;
SendCpp_to_RN.fromCpp((_err, res) => console.log(res));
};
return (
<View style={styles.container}>
<Text> Practice !</Text>
<Button title="C++ to React Native" color="#841584" onPress={onPress} />
</View>
);
};
const styles = StyleSheet.create({
container: {
flex: 1,
justifyContent: 'center',
alignItems: 'center',
},
});
export default App;``````

``react-native run-ios``

1656981060

## 1.新しいreactネイティブアプリを作成し、ターミナルを開いて実行します

``npx react-native init NativeModules``

## 3.C++側での作業

まず、「`Cpp_to_RN.hpp`ファイルを開き、本体のない関数を含むクラスを作成します。

``````#ifndef Cpp_to_RN_hpp
#define Cpp_to_RN_hpp#include <stdio.h>
#include <string>class Cpp_to_RN {
public:
std::string sayHello();
};#endif /* Cpp_to_RN_hpp */``````

``````#include "Cpp_to_RN.hpp"
std::string Cpp_to_RN::sayHello(){
return "Hello from CPP";
}``````

## 4.C++ファイルのラッピングに取り組んでいます。

C ++ファイルをラップしてIOS（swift）側にエクスポートするには

a。ObjectiveCファイルを作成して名前を付けます`Cpp_to_RN.m`

b。ファイルを開き、C++ファイルから`WrapCpp_to_RN.mm` 関数をラップする本文のコンテンツを記述します。`sayHello`

``````#import <Foundation/Foundation.h>
#import "WrapCpp_to_RN.h"
#import "Cpp_to_RN.hpp"@implementation WrapCpp_to_RN- (NSString *) sayHello {
Cpp_to_RN fromCPP;
std::string helloWorldMessage = fromCPP.sayHello();
return [NSString
stringWithCString:helloWorldMessage.c_str()
encoding:NSUTF8StringEncoding];
}
@end``````

c。ヘッダーファイルを作成し、名前を付けます`WrapCpp_to_RN.h`

`wrapSayHello`関数をSwiftファイルにエクスポートします

``````#import <Foundation/Foundation.h>
@interface WrapCpp_to_RN : NSObject
- (NSString *) wrapSayHello;
@end``````

## 5. iOS（Swift）側での作業

C++関数をReactNativeにエクスポートするには

a。Swiftファイルを作成し、名前を付けます`SendCpp_to_RN.swift`

クラス`SendCpp_to_RN`を作成し、次のように宣言します`NSObject`

``````#import <Foundation/Foundation.h>
@interface WrapCpp_to_RN : NSObject
- (NSString *) wrapSayHello;
@end``````

`requiresMainQueueSetup()`アプリケーション実行時の警告を防ぐ関数を作成する

``````#import <Foundation/Foundation.h>
@interface WrapCpp_to_RN : NSObject
- (NSString *) wrapSayHello;
@end``````

`WrapCpp_to_RN()`fromをラップする関数を記述します`WrapCpp_to_RN.mm`

``````import Foundation@objc(SendCpp_to_RN)
class SendCpp_to_RN : NSObject {

@objc static func requiresMainQueueSetup() -> Bool {
return false
}

@objc func fromCpp(_ successCallback: RCTResponseSenderBlock) -> Void {
successCallback([NSNull(), WrapCpp_to_RN().wrapSayHello() as Any])
}}``````

b。Swiftファイルのラップ関数をReactNativeにエクスポートします

を使用してSwiftクラスとその関数をエクスポートするObjectiveCファイルを作成します`Callback`

``````#import <React/RCTBridgeModule.h>
#import <Foundation/Foundation.h>
#import "UIKit/UIKit.h"
@interface RCT_EXTERN_MODULE(SendCpp_to_RN, NSObject)RCT_EXTERN_METHOD(fromCpp:(RCTResponseSenderBlock)successCallback)@end``````

c。SwiftをReactNativeに接続し、`NativeModules-Bridging-Header.h` ファイルを開きます

``#import <React/RCTBridgeModule.h>#import <React/RCTViewManager.h>#import "WrapCpp_to_RN.h"``

## 6.ReactNative側での作業

Swiftクラスとその関数を呼び出す

``````import React from 'react';
import {StyleSheet, Text, View, NativeModules, Button} from 'react-native';const App = () => {
const onPress = () => {
const {SendCpp_to_RN} = NativeModules;
SendCpp_to_RN.fromCpp((_err, res) => console.log(res));
};
return (
<View style={styles.container}>
<Text> Practice !</Text>
<Button title="C++ to React Native" color="#841584" onPress={onPress} />
</View>
);
};
const styles = StyleSheet.create({
container: {
flex: 1,
justifyContent: 'center',
alignItems: 'center',
},
});
export default App;``````

これで完了です。アプリケーションを実行するだけです。

``react-native run-ios``

または、Xcodeの「実行」ボタンをクリックして、実行内容を確認してください。

1656979200

## Comment Exporter Une Fonction De C++ Vers React Native

Aujourd'hui, je continue à partager mon expérience avec le module natif et C++.

Comme nous verrons beaucoup de bibliothèques C/C++ écrire pour les plates-formes mobiles, nous devons les implémenter dans notre application iOS ou React Native. C'est pourquoi je souhaite écrire un article sur la façon d'exporter une fonction de C++ vers React Native, ce qui est facile à comprendre et fait gagner du temps aux débutants. Je vais commencer avec une nouvelle application native réactive

## 1. Créez une nouvelle application native React, ouvrez votre terminal et exécutez

``npx react-native init NativeModules``

## 3. Travailler du côté C++

Créez un nouveau fichier C++ et nommez-le`Cpp_to_RN.cpp`

Lorsque nous créons un nouveau fichier C++, Xcode créera un fichier d'en-tête `Cpp_to_RN.hpp` pour nous

Tout d'abord, ouvrez le fichier " `Cpp_to_RN.hpp`" et créez une classe qui inclut une fonction sans le corps.

``````#ifndef Cpp_to_RN_hpp
#define Cpp_to_RN_hpp#include <stdio.h>
#include <string>class Cpp_to_RN {
public:
std::string sayHello();
};#endif /* Cpp_to_RN_hpp */``````

Ouvrez ensuite le `Cpp_to_RN.cpp`fichier et écrivez une fonction simple " `sayHello()`"

``````#include "Cpp_to_RN.hpp"
std::string Cpp_to_RN::sayHello(){
return "Hello from CPP";
}``````

## 4. Travail sur l'encapsulation du fichier C++.

Pour envelopper les fichiers C++ et les exporter vers le côté IOS (swift)

un. Créez un fichier Objective C et nommez-le`Cpp_to_RN.m`

Renommez le `Cpp_to_RN.m` en `Cpp_to_RN.mm`

b. Ouvrez le `WrapCpp_to_RN.mm` fichier et écrivez le contenu du corps qui encapsulera la fonction `sayHello`à partir du fichier C++.

``````#import <Foundation/Foundation.h>
#import "WrapCpp_to_RN.h"
#import "Cpp_to_RN.hpp"@implementation WrapCpp_to_RN- (NSString *) sayHello {
Cpp_to_RN fromCPP;
std::string helloWorldMessage = fromCPP.sayHello();
return [NSString
stringWithCString:helloWorldMessage.c_str()
encoding:NSUTF8StringEncoding];
}
@end``````

c. Créez un fichier d'en-tête et nommez-le`WrapCpp_to_RN.h`

Exporter la `wrapSayHello`fonction vers le fichier Swift

``````#import <Foundation/Foundation.h>
@interface WrapCpp_to_RN : NSObject
- (NSString *) wrapSayHello;
@end``````

## 5. Travailler du côté iOS (Swift)

Pour exporter la fonction C++ vers React Native

un. Créez un fichier Swift et nommez-le`SendCpp_to_RN.swift`

Remarque : Xcode nous demandera de créer un `NativeModules-Bridging-Header.h`fichier pour nous.

Créez une classe `SendCpp_to_RN`et déclarez-la comme`NSObject`

``````#import <Foundation/Foundation.h>
@interface WrapCpp_to_RN : NSObject
- (NSString *) wrapSayHello;
@end``````

Écrire une fonction `requiresMainQueueSetup()`pour empêcher l'avertissement lorsque nous exécutons l'application

``````#import <Foundation/Foundation.h>
@interface WrapCpp_to_RN : NSObject
- (NSString *) wrapSayHello;
@end``````

Ecrire une fonction pour envelopper le `WrapCpp_to_RN()`from`WrapCpp_to_RN.mm`

``````import Foundation@objc(SendCpp_to_RN)
class SendCpp_to_RN : NSObject {

@objc static func requiresMainQueueSetup() -> Bool {
return false
}

@objc func fromCpp(_ successCallback: RCTResponseSenderBlock) -> Void {
successCallback([NSNull(), WrapCpp_to_RN().wrapSayHello() as Any])
}}``````

b. Exporter une fonction wrap dans un fichier Swift vers React Native

Créez un fichier Objective C pour exporter la classe Swift et sa fonction à l'aide de`Callback`

``````#import <React/RCTBridgeModule.h>
#import <Foundation/Foundation.h>
#import "UIKit/UIKit.h"
@interface RCT_EXTERN_MODULE(SendCpp_to_RN, NSObject)RCT_EXTERN_METHOD(fromCpp:(RCTResponseSenderBlock)successCallback)@end``````

c. Connectez Swift à React Native, ouvrez le `NativeModules-Bridging-Header.h` fichier

``#import <React/RCTBridgeModule.h>#import <React/RCTViewManager.h>#import "WrapCpp_to_RN.h"``

## 6. Travailler du côté React Native

Appelez la classe Swift et ses fonctions

``````import React from 'react';
import {StyleSheet, Text, View, NativeModules, Button} from 'react-native';const App = () => {
const onPress = () => {
const {SendCpp_to_RN} = NativeModules;
SendCpp_to_RN.fromCpp((_err, res) => console.log(res));
};
return (
<View style={styles.container}>
<Text> Practice !</Text>
<Button title="C++ to React Native" color="#841584" onPress={onPress} />
</View>
);
};
const styles = StyleSheet.create({
container: {
flex: 1,
justifyContent: 'center',
alignItems: 'center',
},
});
export default App;``````

Et nous avons terminé, il suffit de lancer l'application

``react-native run-ios``

Ou cliquez simplement sur le bouton "exécuter" sur Xcode et voyez ce que nous avons fait.

J'espère que mon article vous sera utile, merci pour le temps de lecture.

1656977400

## Cómo Exportar Una Función De C++ A React Native

Hoy sigo compartiendo mi experiencia con el Módulo Nativo y C++.

Dado que veremos muchas bibliotecas C/C++ escribiendo para las plataformas móviles, debemos implementarlas en nuestra aplicación iOS o React Native. Por eso quiero escribir un artículo sobre cómo exportar una función de C++ a React Native, que es fácil de entender y ahorra tiempo a los principiantes. Comenzaré con una nueva aplicación nativa de reacción.

## 1. Cree una nueva aplicación nativa de reacción, abra su terminal y ejecute

``npx react-native init NativeModules``

## 3. Trabajando en el lado de C++

Cree un nuevo archivo C++ y asígnele un nombre`Cpp_to_RN.cpp`

Cuando creamos un nuevo archivo C++, Xcode creará un archivo de encabezado `Cpp_to_RN.hpp` para nosotros

Primero, abra el archivo " `Cpp_to_RN.hpp`" y cree una clase que incluya una función sin el cuerpo.

``````#ifndef Cpp_to_RN_hpp
#define Cpp_to_RN_hpp#include <stdio.h>
#include <string>class Cpp_to_RN {
public:
std::string sayHello();
};#endif /* Cpp_to_RN_hpp */``````

Luego abre el `Cpp_to_RN.cpp`archivo y escribe una función simple “ `sayHello()`

``````#include "Cpp_to_RN.hpp"
std::string Cpp_to_RN::sayHello(){
return "Hello from CPP";
}``````

## 4. Trabajando en el archivo Wrapping C++.

Para envolver los archivos C++ y exportarlos al lado IOS (swift)

una. Cree un archivo Objective C y asígnele un nombre`Cpp_to_RN.m`

Renombrar el `Cpp_to_RN.m` a `Cpp_to_RN.mm`

b. Abra el `WrapCpp_to_RN.mm` archivo y escriba el contenido del cuerpo que envolverá la función `sayHello`del archivo C++.

``````#import <Foundation/Foundation.h>
#import "WrapCpp_to_RN.h"
#import "Cpp_to_RN.hpp"@implementation WrapCpp_to_RN- (NSString *) sayHello {
Cpp_to_RN fromCPP;
std::string helloWorldMessage = fromCPP.sayHello();
return [NSString
stringWithCString:helloWorldMessage.c_str()
encoding:NSUTF8StringEncoding];
}
@end``````

C. Cree un archivo de encabezado y asígnele un nombre`WrapCpp_to_RN.h`

Exportar la `wrapSayHello`función al archivo Swift

``````#import <Foundation/Foundation.h>
@interface WrapCpp_to_RN : NSObject
- (NSString *) wrapSayHello;
@end``````

## 5. Trabajando en el lado de iOS (Swift)

Para exportar la función C++ a React Native

una. Cree un archivo Swift y asígnele un nombre`SendCpp_to_RN.swift`

Nota: Xcode nos pedirá que creemos un `NativeModules-Bridging-Header.h`archivo para nosotros.

Crear una clase `SendCpp_to_RN`y declararla como`NSObject`

``````#import <Foundation/Foundation.h>
@interface WrapCpp_to_RN : NSObject
- (NSString *) wrapSayHello;
@end``````

Escribir una función `requiresMainQueueSetup()`para evitar advertencias cuando ejecutamos la aplicación.

``````#import <Foundation/Foundation.h>
@interface WrapCpp_to_RN : NSObject
- (NSString *) wrapSayHello;
@end``````

Escriba una función para envolver el `WrapCpp_to_RN()`from`WrapCpp_to_RN.mm`

``````import Foundation@objc(SendCpp_to_RN)
class SendCpp_to_RN : NSObject {

@objc static func requiresMainQueueSetup() -> Bool {
return false
}

@objc func fromCpp(_ successCallback: RCTResponseSenderBlock) -> Void {
successCallback([NSNull(), WrapCpp_to_RN().wrapSayHello() as Any])
}}``````

b. Exporte una función de ajuste en un archivo Swift a React Native

Cree un archivo Objective C para exportar la clase Swift y su función usando`Callback`

``````#import <React/RCTBridgeModule.h>
#import <Foundation/Foundation.h>
#import "UIKit/UIKit.h"
@interface RCT_EXTERN_MODULE(SendCpp_to_RN, NSObject)RCT_EXTERN_METHOD(fromCpp:(RCTResponseSenderBlock)successCallback)@end``````

C. Conecte Swift a React Native, abra el `NativeModules-Bridging-Header.h` archivo

``#import <React/RCTBridgeModule.h>#import <React/RCTViewManager.h>#import "WrapCpp_to_RN.h"``

## 6. Trabajando en el lado de React Native

Llame a la clase Swift y sus funciones

``````import React from 'react';
import {StyleSheet, Text, View, NativeModules, Button} from 'react-native';const App = () => {
const onPress = () => {
const {SendCpp_to_RN} = NativeModules;
SendCpp_to_RN.fromCpp((_err, res) => console.log(res));
};
return (
<View style={styles.container}>
<Text> Practice !</Text>
<Button title="C++ to React Native" color="#841584" onPress={onPress} />
</View>
);
};
const styles = StyleSheet.create({
container: {
flex: 1,
justifyContent: 'center',
alignItems: 'center',
},
});
export default App;``````

Y listo, solo ejecuta la aplicación

``react-native run-ios``

O simplemente haga clic en el botón "ejecutar" en Xcode y vea lo que hemos hecho.

Espero que mi artículo te sea útil, gracias por tu tiempo de lectura.

1656981000

## Cách Xuất Một Hàm Từ C ++ Sang React Native

Hôm nay, tôi tiếp tục chia sẻ kinh nghiệm của mình với Native Module và C ++.

Vì chúng ta sẽ thấy rất nhiều thư viện C / C ++ viết cho nền tảng di động, chúng ta cần triển khai chúng cho ứng dụng iOS hoặc React Native của mình. Đó là lý do mình muốn viết một bài hướng dẫn cách export một hàm từ C ++ sang React Native dễ hiểu và tiết kiệm thời gian cho người mới bắt đầu. Tôi sẽ bắt đầu với một ứng dụng gốc phản ứng mới

## 1. Tạo một ứng dụng gốc phản ứng mới, mở thiết bị đầu cuối của bạn và chạy

``npx react-native init NativeModules``

## 3. Làm việc trên C ++

Tạo một tệp C ++ mới và đặt tên cho nó`Cpp_to_RN.cpp`

Khi chúng tôi tạo tệp C ++ mới, Xcode sẽ tạo tệp tiêu đề `Cpp_to_RN.hpp` cho chúng tôi

Đầu tiên, mở tệp `Cpp_to_RN.hpp`“” và tạo một lớp bao gồm một hàm không có phần thân.

``````#ifndef Cpp_to_RN_hpp
#define Cpp_to_RN_hpp#include <stdio.h>
#include <string>class Cpp_to_RN {
public:
std::string sayHello();
};#endif /* Cpp_to_RN_hpp */``````

Sau đó, mở `Cpp_to_RN.cpp`tệp và viết một hàm đơn giản “ `sayHello()`

``````#include "Cpp_to_RN.hpp"
std::string Cpp_to_RN::sayHello(){
return "Hello from CPP";
}``````

## 4. Thao tác trên Wrapping C ++ file.

Để bọc các tệp C ++ và xuất chúng sang phía IOS (nhanh chóng)

một. Tạo một tệp Objective C và đặt tên cho nó`Cpp_to_RN.m`

Đổi tên `Cpp_to_RN.m` thành `Cpp_to_RN.mm`

b. Mở `WrapCpp_to_RN.mm` tệp và viết nội dung phần nội dung sẽ bọc hàm `sayHello`từ tệp C ++.

``````#import <Foundation/Foundation.h>
#import "WrapCpp_to_RN.h"
#import "Cpp_to_RN.hpp"@implementation WrapCpp_to_RN- (NSString *) sayHello {
Cpp_to_RN fromCPP;
std::string helloWorldMessage = fromCPP.sayHello();
return [NSString
stringWithCString:helloWorldMessage.c_str()
encoding:NSUTF8StringEncoding];
}
@end``````

c. Tạo một tệp tiêu đề và đặt tên cho nó`WrapCpp_to_RN.h`

Xuất `wrapSayHello`hàm sang tệp Swift

``````#import <Foundation/Foundation.h>
@interface WrapCpp_to_RN : NSObject
- (NSString *) wrapSayHello;
@end``````

## 5. Làm việc trên iOS (Swift)

Để xuất hàm C ++ sang React Native

một. Tạo một tệp Swift và đặt tên cho nó`SendCpp_to_RN.swift`

Lưu ý: Xcode sẽ yêu cầu chúng tôi tạo một `NativeModules-Bridging-Header.h`tệp cho chúng tôi.

Tạo một lớp `SendCpp_to_RN`và khai báo nó là`NSObject`

``````#import <Foundation/Foundation.h>
@interface WrapCpp_to_RN : NSObject
- (NSString *) wrapSayHello;
@end``````

Viết một hàm `requiresMainQueueSetup()`để ngăn cảnh báo khi chúng tôi chạy ứng dụng

``````#import <Foundation/Foundation.h>
@interface WrapCpp_to_RN : NSObject
- (NSString *) wrapSayHello;
@end``````

Viết một hàm để bọc `WrapCpp_to_RN()`từ`WrapCpp_to_RN.mm`

``````import Foundation@objc(SendCpp_to_RN)
class SendCpp_to_RN : NSObject {

@objc static func requiresMainQueueSetup() -> Bool {
return false
}

@objc func fromCpp(_ successCallback: RCTResponseSenderBlock) -> Void {
successCallback([NSNull(), WrapCpp_to_RN().wrapSayHello() as Any])
}}``````

b. Xuất một hàm bọc trong tệp Swift sang React Native

Tạo một tệp Objective C để xuất lớp Swift và chức năng của nó bằng cách sử dụng`Callback`

``````#import <React/RCTBridgeModule.h>
#import <Foundation/Foundation.h>
#import "UIKit/UIKit.h"
@interface RCT_EXTERN_MODULE(SendCpp_to_RN, NSObject)RCT_EXTERN_METHOD(fromCpp:(RCTResponseSenderBlock)successCallback)@end``````

c. Kết nối Swift với React Native, mở `NativeModules-Bridging-Header.h` tệp

``#import <React/RCTBridgeModule.h>#import <React/RCTViewManager.h>#import "WrapCpp_to_RN.h"``

## 6. Làm việc ở phía React Native

Gọi lớp Swift và các chức năng của nó

``````import React from 'react';
import {StyleSheet, Text, View, NativeModules, Button} from 'react-native';const App = () => {
const onPress = () => {
const {SendCpp_to_RN} = NativeModules;
SendCpp_to_RN.fromCpp((_err, res) => console.log(res));
};
return (
<View style={styles.container}>
<Text> Practice !</Text>
<Button title="C++ to React Native" color="#841584" onPress={onPress} />
</View>
);
};
const styles = StyleSheet.create({
container: {
flex: 1,
justifyContent: 'center',
alignItems: 'center',
},
});
export default App;``````

Và chúng tôi đã hoàn tất, chỉ cần chạy ứng dụng

``react-native run-ios``

Hoặc chỉ cần nhấp vào nút “chạy” trên Xcode và xem những gì chúng tôi đã làm.

Tôi hy vọng bài viết của tôi hữu ích cho bạn, cảm ơn bạn đã dành thời gian đọc.