Fleta  Dickens

Fleta Dickens

1656802800

A Rollup Plugin Which Imports JPG, PNG, GIF, SVG, and WebP Files.

@rollup/plugin-image

馃崳 A Rollup plugin which imports JPG, PNG, GIF, SVG, and WebP files.

Images are encoded using base64, which means they will be 33% larger than the size on disk. You should therefore only use this for small images where the convenience of having them available on startup (e.g. rendering immediately to a canvas without co-ordinating asynchronous loading of several images) outweighs the cost.

Requirements

This plugin requires an LTS Node version (v8.0.0+) and Rollup v1.20.0+.

Install

Using npm:

npm install @rollup/plugin-image --save-dev

Usage

Assuming a src/index.js exists and contains code like the following:

import logo from './rollup.png';

console.log(logo);

Create a rollup.config.js configuration file and import the plugin:

import image from '@rollup/plugin-image';

export default {
  input: 'src/index.js',
  output: {
    dir: 'output',
    format: 'cjs'
  },
  plugins: [image()]
};

Then call rollup either via the CLI or the API.

Once the bundle is executed, the console.log will display the Base64 encoded representation of the image.

Options

dom

Type: Boolean
Default: false

If true, instructs the plugin to generate an ES Module which exports a DOM Image which can be used with a browser's DOM. Otherwise, the plugin generates an ES Module which exports a default const containing the Base64 representation of the image.

Using this option set to true, the export can be used as such:

import logo from './rollup.png';
document.body.appendChild(logo);

exclude

Type: String | Array[...String]
Default: null

A minimatch pattern, or array of patterns, which specifies the files in the build the plugin should ignore. By default no files are ignored.

include

Type: String | Array[...String]
Default: null

A minimatch pattern, or array of patterns, which specifies the files in the build the plugin should operate on. By default all files are targeted.

Meta

CONTRIBUTING

LICENSE (MIT)


Author: rollup
Source Code: https://github.com/rollup/plugins/
License: 

#vue #vite #typescript #javascript #Rollup 

What is GEEK

Buddha Community

A Rollup Plugin Which Imports JPG, PNG, GIF, SVG, and WebP Files.

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

2. Abra Xcode y vaya a NativeModules/ios/NativeModule.xcworkspace

3. Trabajando en el lado de C++

Cree un nuevo archivo C++ y as铆gnele un nombreCpp_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.cpparchivo 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 nombreCpp_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 sayHellodel 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 nombreWrapCpp_to_RN.h

Exportar la wrapSayHellofunci贸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 nombreSendCpp_to_RN.swift

Nota: Xcode nos pedir谩 que creemos un NativeModules-Bridging-Header.harchivo para nosotros.

Crear una clase SendCpp_to_RNy declararla comoNSObject

#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()fromWrapCpp_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 usandoCallback

#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.

 Fuente: https://betterprogramming.pub/native-modules-export-c-function-to-react-native-for-beginners-77e89934b210

#cpp #cplusplus #react 

闁㈡暟銈扖++銇嬨倝ReactNative銇偍銈偣銉濄兗銉堛仚銈嬫柟娉

浠婃棩銈傘併儘銈ゃ儐銈c儢銉€偢銉ャ兗銉仺C++銇с伄绲岄〒銈掑叡鏈夈仐缍氥亼銇︺亜銇俱仚銆

澶氥亸銇瓹/C ++銉┿偆銉栥儵銉亴銉€儛銈ゃ儷銉椼儵銉冦儓銉曘偐銉笺儬鐢ㄣ伀浣滄垚銇曘倢銇︺亜銈嬨伄銇с併仢銈屻倝銈抜OS銇俱仧銇疪eactNative銈€儣銉偙銉笺偡銉с兂銇疅瑁呫仚銈嬪繀瑕併亴銇傘倞銇俱仚銆傘仢銇仧銈併侀枹鏁般倰C++銇嬨倝ReactNative銇偍銈偣銉濄兗銉堛仚銈嬫柟娉曘伀銇ゃ亜銇︺伄瑷樹簨銈掓浉銇嶃仧銇勩仺鎬濄亜銇俱仚銆傘亾銈屻伅銆佺悊瑙c仐銈勩仚銇忋佸垵蹇冭呫伄鏅傞枔銈掔瘈绱勩仹銇嶃伨銇欍傛柊銇椼亜react銉嶃偆銉嗐偅銉栥偄銉椼儶銈便兗銈枫儳銉炽亱銈夊銈併伨銇

1.鏂般仐銇剅eact銉嶃偆銉嗐偅銉栥偄銉椼儶銈掍綔鎴愩仐銆併偪銉笺儫銉娿儷銈掗枊銇勩仸瀹熻銇椼伨銇

npx react-native init NativeModules

2. Xcode銈掗枊銇嶃丯ativeModules / ios/NativeModule.xcworkspace銇Щ鍕曘仐銇俱仚

3.C++鍋淬仹銇綔妤

鏂般仐銇凜++銉曘偂銈ゃ儷銈掍綔鎴愩仐銆佸悕鍓嶃倰浠樸亼銇俱仚Cpp_to_RN.cpp

鏂般仐銇凜++銉曘偂銈ゃ儷銈掍綔鎴愩仚銈嬨仺銆乆code銇儤銉冦儉銉笺儠銈°偆銉Cpp_to_RN.hpp 銈掍綔鎴愩仐銇俱仚

銇俱仛銆併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 */

娆°伀銆併儠銈°偆銉倰闁嬨亜銇Cpp_to_RN.cpp銆佸崢绱斻仾闁㈡暟銆sayHello()銆嶃倰瑷樿堪銇椼伨銇欍

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

4.C++銉曘偂銈ゃ儷銇儵銉冦償銉炽偘銇彇銈婄祫銈撱仹銇勩伨銇欍

C ++銉曘偂銈ゃ儷銈掋儵銉冦儣銇椼仸IOS锛坰wift锛夊伌銇偍銈偣銉濄兗銉堛仚銈嬨伀銇

a銆侽bjectiveC銉曘偂銈ゃ儷銈掍綔鎴愩仐銇﹀悕鍓嶃倰浠樸亼銇俱仚Cpp_to_RN.m

鍚嶅墠銈掋伀澶夋洿Cpp_to_RN.m 銇椼伨銇 Cpp_to_RN.mm

b銆傘儠銈°偆銉倰闁嬨亶銆丆++銉曘偂銈ゃ儷銇嬨倝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闁㈡暟銈扴wift銉曘偂銈ゃ儷銇偍銈偣銉濄兗銉堛仐銇俱仚

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

5. iOS锛圫wift锛夊伌銇с伄浣滄キ

C++闁㈡暟銈扲eactNative銇偍銈偣銉濄兗銉堛仚銈嬨伀銇

a銆係wift銉曘偂銈ゃ儷銈掍綔鎴愩仐銆佸悕鍓嶃倰浠樸亼銇俱仚SendCpp_to_RN.swift

娉細Xcode銇NativeModules-Bridging-Header.h銉曘偂銈ゃ儷銈掍綔鎴愩仚銈嬨倛銇嗐伀瑕佹眰銇椼伨銇欍

銈儵銈SendCpp_to_RN銈掍綔鎴愩仐銆佹銇倛銇嗐伀瀹h█銇椼伨銇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銆係wift銉曘偂銈ゃ儷銇儵銉冦儣闁㈡暟銈扲eactNative銇偍銈偣銉濄兗銉堛仐銇俱仚

銈掍娇鐢ㄣ仐銇wift銈儵銈广仺銇濄伄闁㈡暟銈掋偍銈偣銉濄兗銉堛仚銈婳bjectiveC銉曘偂銈ゃ儷銈掍綔鎴愩仐銇俱仚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銆係wift銈扲eactNative銇帴缍氥仐銆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

銇俱仧銇乆code銇屽疅琛屻嶃儨銈裤兂銈掋偗銉儍銈仐銇︺佸疅琛屽唴瀹广倰纰鸿獚銇椼仸銇忋仩銇曘亜銆

绉併伄瑷樹簨銇屻亰褰广伀绔嬨仸銇板垢銇勩仹銇欍傘亰瑾伩銇勩仧銇犮亶銇傘倞銇屻仺銇嗐仈銇栥亜銇俱仚銆

 銈姐兗銈癸細https 锛//betterprogramming.pub/native-modules-export-c-function-to-react-native-for-beginners-77e89934b210

#cpp #cplusplus #react 

Hoang  Ha

Hoang Ha

1656981000

C谩ch Xu岷 M峄檛 H脿m T峄 C ++ Sang React Native

H么m nay, t么i ti岷縫 t峄 chia s岷 kinh nghi峄噈 c峄 m矛nh v峄沬 Native Module v脿 C ++.

V矛 ch煤ng ta s岷 th岷 r岷 nhi峄乽 th瓢 vi峄噉 C / C ++ vi岷縯 cho n峄乶 t岷g di 膽峄檔g, ch煤ng ta c岷 tri峄僴 khai ch煤ng cho 峄﹏g d峄g iOS ho岷穋 React Native c峄 m矛nh. 膼贸 l脿 l媒 do m矛nh mu峄憂 vi岷縯 m峄檛 b脿i h瓢峄沶g d岷玭 c谩ch export m峄檛 h脿m t峄 C ++ sang React Native d峄 hi峄僽 v脿 ti岷縯 ki峄噈 th峄漣 gian cho ng瓢峄漣 m峄沬 b岷痶 膽岷. T么i s岷 b岷痶 膽岷 v峄沬 m峄檛 峄﹏g d峄g g峄慶 ph岷 峄﹏g m峄沬

1. T岷 m峄檛 峄﹏g d峄g g峄慶 ph岷 峄﹏g m峄沬, m峄 thi岷縯 b峄 膽岷 cu峄慽 c峄 b岷 v脿 ch岷

npx react-native init NativeModules

2. M峄 Xcode v脿 膽i峄乽 h瓢峄沶g 膽岷縩 NativeModules / ios / NativeModule.xcworkspace

3. L脿m vi峄嘽 tr锚n C ++

T岷 m峄檛 t峄噋 C ++ m峄沬 v脿 膽岷穞 t锚n cho n贸Cpp_to_RN.cpp

Khi ch煤ng t么i t岷 t峄噋 C ++ m峄沬, Xcode s岷 t岷 t峄噋 ti锚u 膽峄 Cpp_to_RN.hpp cho ch煤ng t么i

膼岷 ti锚n, m峄 t峄噋 Cpp_to_RN.hpp鈥溾 v脿 t岷 m峄檛 l峄沺 bao g峄搈 m峄檛 h脿m kh么ng c贸 ph岷 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.cppt峄噋 v脿 vi岷縯 m峄檛 h脿m 膽啤n gi岷 鈥 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 t峄噋 C ++ v脿 xu岷 ch煤ng sang ph铆a IOS (nhanh ch贸ng)

m峄檛. T岷 m峄檛 t峄噋 Objective C v脿 膽岷穞 t锚n cho n贸Cpp_to_RN.m

膼峄昳 t锚n Cpp_to_RN.m th脿nh Cpp_to_RN.mm

b. M峄 WrapCpp_to_RN.mm t峄噋 v脿 vi岷縯 n峄檌 dung ph岷 n峄檌 dung s岷 b峄峜 h脿m sayHellot峄 t峄噋 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岷 m峄檛 t峄噋 ti锚u 膽峄 v脿 膽岷穞 t锚n cho n贸WrapCpp_to_RN.h

Xu岷 wrapSayHelloh脿m sang t峄噋 Swift

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

5. L脿m vi峄嘽 tr锚n iOS (Swift)

膼峄 xu岷 h脿m C ++ sang React Native

m峄檛. T岷 m峄檛 t峄噋 Swift v脿 膽岷穞 t锚n cho n贸SendCpp_to_RN.swift

L瓢u 媒: Xcode s岷 y锚u c岷 ch煤ng t么i t岷 m峄檛 NativeModules-Bridging-Header.ht峄噋 cho ch煤ng t么i.

T岷 m峄檛 l峄沺 SendCpp_to_RNv脿 khai b谩o n贸 l脿NSObject

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

Vi岷縯 m峄檛 h脿m requiresMainQueueSetup()膽峄 ng膬n c岷h b谩o khi ch煤ng t么i ch岷 峄﹏g d峄g

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

Vi岷縯 m峄檛 h脿m 膽峄 b峄峜 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岷 m峄檛 h脿m b峄峜 trong t峄噋 Swift sang React Native

T岷 m峄檛 t峄噋 Objective C 膽峄 xu岷 l峄沺 Swift v脿 ch峄ヽ n膬ng c峄 n贸 b岷眓g c谩ch s峄 d峄gCallback

#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岷縯 n峄慽 Swift v峄沬 React Native, m峄 NativeModules-Bridging-Header.h t峄噋

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

6. L脿m vi峄嘽 峄 ph铆a React Native

G峄峣 l峄沺 Swift v脿 c谩c ch峄ヽ n膬ng c峄 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岷, ch峄 c岷 ch岷 峄﹏g d峄g

react-native run-ios

Ho岷穋 ch峄 c岷 nh岷 v脿o n煤t 鈥渃h岷鈥 tr锚n Xcode v脿 xem nh峄痭g g矛 ch煤ng t么i 膽茫 l脿m.

T么i hy v峄峮g b脿i vi岷縯 c峄 t么i h峄痷 铆ch cho b岷, c岷 啤n b岷 膽茫 d脿nh th峄漣 gian 膽峄峜.

 Ngu峄搉: https://betterprogramming.pub/native-modules-export-c- Ch峄ヽ n膬ng-to-react-native-for-beginners-77e89934b210

#cpp #cplusplus #react 

榛 椋

榛 椋

1656984600

濡備綍灏嗗嚱鏁颁粠 C++ 瀵煎嚭鍒 React Native

浠婂ぉ锛屾垜缁х画鍒嗕韩鎴戝湪 Native Module 鍜 C++ 鏂归潰鐨勭粡楠屻

鐢变簬鎴戜滑灏嗙湅鍒板緢澶氫负绉诲姩骞冲彴缂栧啓鐨 C/C++ 搴擄紝鍥犳鎴戜滑闇瑕佸皢瀹冧滑瀹炵幇鍒版垜浠殑 iOS 鎴 React Native 搴旂敤绋嬪簭涓傝繖灏辨槸涓轰粈涔堟垜鎯冲啓涓绡囧叧浜庡浣曞皢涓涓嚱鏁颁粠 C++ 瀵煎嚭鍒 React Native 鐨勬枃绔狅紝瀹冩槗浜庣悊瑙e苟涓斾负鍒濆鑰呰妭鐪佷簡鏃堕棿銆傛垜灏嗕粠涓涓柊鐨 react native 搴旂敤绋嬪簭寮濮

1.鏂板缓涓涓猺eact native app锛屾墦寮浣犵殑缁堢杩愯

npx react-native init NativeModules

2. 鎵撳紑 Xcode 骞跺鑸埌 NativeModules/ios/NativeModule.xcworkspace

3. 鍦 C++ 绔伐浣

鍒涘缓涓涓柊鐨 C++ 鏂囦欢骞跺懡鍚Cpp_to_RN.cpp

褰撴垜浠垱寤轰竴涓柊鐨 C++ 鏂囦欢鏃讹紝Xcode 浼Cpp_to_RN.hpp 涓烘垜浠垱寤轰竴涓ご鏂囦欢

棣栧厛锛屾墦寮鈥 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 */

鐒跺悗鎵撳紑Cpp_to_RN.cpp鏂囦欢锛屽啓涓涓畝鍗曠殑鍑芥暟鈥 sayHello()

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

4. 澶勭悊鍖呰 C++ 鏂囦欢銆

鍖呰 C++ 鏂囦欢骞跺皢瀹冧滑瀵煎嚭鍒 IOS (swift) 绔

涓涓傚垱寤轰竴涓狾bjective C鏂囦欢骞跺懡鍚Cpp_to_RN.m

閲嶅懡鍚Cpp_to_RN.m Cpp_to_RN.mm

婀俱傛墦寮WrapCpp_to_RN.mm 鏂囦欢骞剁紪鍐欏皢鍖呰sayHelloC++ 鏂囦欢涓殑鍑芥暟鐨勬鏂囧唴瀹广

#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++ 鍑芥暟瀵煎嚭鍒 React Native

涓涓傚垱寤轰竴涓 Swift 鏂囦欢骞跺懡鍚SendCpp_to_RN.swift

娉ㄦ剰锛歑code 浼氳姹傛垜浠负鎴戜滑鍒涘缓涓涓NativeModules-Bridging-Header.h鏂囦欢銆

鍒涘缓涓涓被SendCpp_to_RN骞跺皢鍏跺0鏄庝负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()fromWrapCpp_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])
    }}

婀俱傚皢 Swift 鏂囦欢涓殑鍖呰鍑芥暟瀵煎嚭鍒 React Native

鍒涘缓涓涓 Objective C 鏂囦欢浠ュ鍑 Swift 绫诲強鍏跺嚱鏁帮紝浣跨敤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 杩炴帴鍒 React Native锛屾墦寮NativeModules-Bridging-Header.h 鏂囦欢

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

6. 鍦 React Native 鏂归潰宸ヤ綔

璋冪敤 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 涓婄殑鈥滆繍琛屸濇寜閽紝鐪嬬湅鎴戜滑鍋氫簡浠涔堛

甯屾湜鎴戠殑鏂囩珷瀵规偍鏈夋墍甯姪锛屾劅璋㈡偍鐨勯槄璇绘椂闂淬

 鏉ユ簮锛https ://betterprogramming.pub/native-modules-export-c-function-to-react-native-for-beginners-77e89934b210

#cpp #cplusplus #react 

Como Exportar Uma Fun莽茫o De C++ Para React Native

Hoje, continuo compartilhando minha experi锚ncia com o M贸dulo Nativo e C++.

Como veremos muitas bibliotecas C/C++ escrevendo para plataformas m贸veis, precisamos implement谩-las em nosso aplicativo iOS ou React Native. 脡 por isso que quero escrever um artigo sobre como exportar uma fun莽茫o de C++ para React Native, que 茅 f谩cil de entender e economiza tempo para iniciantes. Vou come莽ar com um novo aplicativo nativo de rea莽茫o

1. Crie um novo aplicativo nativo de rea莽茫o, abra seu terminal e execute

npx react-native init NativeModules

2. Abra o Xcode e navegue at茅 NativeModules/ios/NativeModule.xcworkspace

3. Trabalhando no lado C++

Crie um novo arquivo C++ e nomeie-oCpp_to_RN.cpp

Quando criamos um novo arquivo C++, o Xcode criar谩 um arquivo de cabe莽alho Cpp_to_RN.hpp para n贸s

Primeiro, abra o arquivo 鈥 Cpp_to_RN.hpp e crie uma classe que inclua uma fun莽茫o sem o corpo.

#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 */

Em seguida, abra o Cpp_to_RN.cpparquivo e escreva uma fun莽茫o simples 鈥 sayHello()

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

4. Trabalhando no arquivo C++ de encapsulamento.

Para encapsular os arquivos C++ e export谩-los para o lado IOS (swift)

uma. Crie um arquivo Objective C e nomeie-oCpp_to_RN.m

Renomeie o Cpp_to_RN.m para Cpp_to_RN.mm

b. Abra o WrapCpp_to_RN.mm arquivo e escreva o conte煤do do corpo que envolver谩 a fun莽茫o sayHellodo arquivo 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. Crie um arquivo de cabe莽alho e nomeie-oWrapCpp_to_RN.h

Exporte a wrapSayHellofun莽茫o para o arquivo Swift

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

5. Trabalhando no lado iOS (Swift)

Para exportar a fun莽茫o C++ para React Native

uma. Crie um arquivo Swift e nomeie-oSendCpp_to_RN.swift

Observa莽茫o: o Xcode nos pedir谩 para criar um NativeModules-Bridging-Header.harquivo para n贸s.

Crie uma classe SendCpp_to_RNe declare-a comoNSObject

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

Escreva uma fun莽茫o requiresMainQueueSetup()para evitar avisos quando executamos o aplicativo

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

Escreva uma fun莽茫o para envolver o WrapCpp_to_RN()fromWrapCpp_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 uma fun莽茫o wrap no arquivo Swift para React Native

Crie um arquivo Objective C para exportar a classe Swift e sua fun莽茫o usandoCallback

#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 o Swift ao React Native, abra o NativeModules-Bridging-Header.h arquivo

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

6. Trabalhando no lado React Native

Chame a classe Swift e suas fun莽玫es

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;

E pronto, basta executar o aplicativo

react-native run-ios

Ou apenas clique no bot茫o 鈥渆xecutar鈥 no Xcode e veja o que fizemos.

Espero que meu artigo seja 煤til para voc锚, obrigado pelo tempo de leitura.

 Fonte: https://betterprogramming.pub/native-modules-export-c-function-to-react-native-for-beginners-77e89934b210

#cpp #cplusplus #react