1668077298

# Introduction To Matplotlib In Data Science And Its Importance

A big component of gaining a career in the data science profession is learning new languages and data science technologies. Python is a popular tool and programming language in the data science field. It could be helpful to become familiar with the many Python packages available while working on data science projects.

In the field of data science, the Matplotlib program is frequently used to produce unique graphics and visualizations that highlight the findings of a data research project. These are just a handful of the numerous benefits of adding this Python module to your collection of data science tools.

In this essay, we shall learn about Matplotlib and its significance in data science. Let's get going.

## Matplotlib: A Quick Overview

Python's Matplotlib library is commonly used to create two-dimensional graphs and other types of data visualizations and models. The NumPy library, also used in Python to carry out mathematical calculations, was supplemented by Matplotlib in 2003.

You may quickly produce visually appealing results from your statistical procedures and investigations with Matplotlib. Like many other open-source data science tools, the Matplotlib package benefits from the work of a thriving community of Python developers and users.

On the blog with the same name, both professionals and students in the field of data science may discover articles and examples illustrating how they can utilize Matplotlib in their work.

## Matplotlib's Adoption by the Data Science Community

Many of Matplotlib's useful data science functions are related to data visualization or modeling, as it is a frequently used tool for plotting and charting graphs. The list below includes a few of this versatile Python package's numerous reporting and data storytelling uses.

### Making Charts and Graphs

Before attempting to create data visualizations using the Matplotlib software, one must be familiar with the process of plotting charts and graphs. Making a graph or arranging data points or variables along an x-y axis to show their association is known as plotting in the field of data science.

Matplotlib's Plot function is required to create any graphs or visualizations specified by the library. Data scientists who want to perform a visual analysis of their data benefit from plotting since it allows them to study correlations that emerge within the dataset and make deductions based on factors like slope and clustering.

Each data visualization style has a related method or function you can access after importing Matplotlib into your favorite Python environment. To chart data, Matplotlib offers a variety of helpful ways, such as "plt.hst()" for creating histograms, "plt.bar()" for creating bar charts, and "plt.pie()" for creating pie charts.

The syntax of Matplotlib will be familiar and easy to understand for data scientists proficient in statistical analysis and common mathematical operations. For further information, refer to the data science course in Chennai, designed to meet the demands of industry.

Thanks to these particular features, data scientists may experiment with their data using a range of graphs and visualizations to see which best communicates their results.

## Data Presentation in Visual Form

You may quickly create a variety of graphs, charts, and other visual representations of data with Matplotlib. The Matplotlib toolkit includes tools for making bar charts, pie charts, and other diagrams to help data scientists graphically describe their results.

Draw a set of points along an x-y axis and link them with a line to make a line plot.

Scatter plots, which are similar to line plots but lack the connecting line, display the placement of several data points on a graph (which is more common among a dataset that has more variability).

In a histogram, bars of differing heights are stacked on top of one another to show the data distribution.

In addition to traditional visualizations, Matplotlib offers a broad range of innovative graphing alternatives. Pie charts and box plots are two forms of graphs that might make you stand out to your viewers.

The common pie chart is beneficial for communicating the outcomes of a data analysis effort focused on comparing portions.

## Graphics, animations, and images

The Matplotlib package has tools for altering the colors, creating animations, and labeling the axes of your graphs, among other graph customization options.

You may choose the best color scheme for presenting your data or artwork using the colormaps included in the library. After you've made changes to your graphs and pictures, Matplotlib allows you to add motion.

These animations may be used to create two-dimensional and three-dimensional graphics, enhance the interactivity of any data visualization and even show modifications or updates to an ongoing data analysis project.

Because of its adaptability as a visualization and model-building tool, Matplotlib may also be used to produce other common visuals and images in the data science industry.

By creating graphics like heat maps, data scientists may visualize data on particular demography, healthcare trends, or even the weather and natural disasters.

Given that its output can be incorporated into a broad range of platforms and applications, Matplotlib is a helpful tool for creating, sharing, and displaying visual representations of data.

## Last Words

The last sections of the article are now complete. We discussed data visualization, plotting charts and graphs, and utilizing pictures and animations to understand Matplotlib and its significance in data science. If you want to master data visualization, join the best data analytics course in Chennai, and become a certified data analyst.

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の「実行」ボタンをクリックして、実行内容を確認してください。

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.

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.

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.

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``