SECRET OF CSS

Native Modules: Export C Functions to React Native | by Wynne Tran | Jun, 2022


Convert C libraries to React Native

The purpose of this article is to help beginners save time when they are working with Native Module for the first time. Since we will be seeing a lot of C libraries for mobile, and as a developer, you will have to convert them to iOS or react native platforms.

To continue my Native Modules lists, I’ve written this article to describe how we wrap and export a function from the C language to React Native in mobile development. As usual, we start with a new react native app.

Open your terminal and run:

npx react-native init NativeModules

Now navigate to:

NativeModules/ios/NativeModule.xcworkspace

We create a new folder and create a new c file C_to_RN.c:

1*RI

When we click “next”, Xcode will ask us to create a header file:

1*qayTKWyXpwCM 3fPEIlRrA

We will begin C_to_RN.c first, and write a simple function:

// C_to_RN.clong factorial(int n) {    
if (n == 0 || n == 1) return 1;
return n * factorial(n-1);
}
1*Euwp93L4qVeerViS5hcK g

Continue, we put this function to the header file:

// C_to_RN.hlong factorial(int n);
1*7hwTS2U3XfEDc05uY1292A
  • Create a new swift file and name it C_to_RN.swift
  • When creating a new swift file, Xcode will as us create the NativeModules-Bridging-Header.h
1*spXL UClungiDvAaZ1ciLg

Now, in the swift file, we declare a C_to_RN class as NSObject and export this class to the Objective-C file ( we will create in the next step) @objc(C_to_RN).

// C_to_RN.swift@objc(C_to_RN)
class
C_to_RN : NSObject {
}

Next, write 2 functions:

  • To prevent a warning when we run the react native app.
  • To wrap a “factorial” function from C_to_RN.c
// C_to_RN.swift@objc static func requiresMainQueueSetup() -> Bool {return false }@objc func WrapFactorial(_ num:(Int), callback: RCTResponseSenderBlock) {     callback([NSNull(), factorial(Int32(num)) as Any])}
1*bswM1jNq5fBeFFgMYCSQGg

5. Create a new objective c file and name it “C_to_RN.m”

Of course, if we want to export a function from Swift to React Native, we need to export it via an Objective-C file.

If you are a fresher without experience in Swift or Objective C, please look over my topics, here:

How to export a function from Objective C to react-native:

How to export a function from Swift file to react native:

Come back to our task, we will create a new Objective C file and export the C_to_RN class and WrapFactorial function from the Swift file.

// C_to_RN.m#import <Foundation/Foundation.h>
#import <React/RCTBridgeModule.h>
@interface RCT_EXTERN_MODULE(C_to_RN, NSObject)RCT_EXTERN_METHOD(WrapFactorial: (int)num callback: (RCTResponseSenderBlock)callback;)@end

The next step is to bridge iOS native to react-native via NativeModules-Bridging-Header.h:

// NativeModules-Bridging-Header.h#import <React/RCTBridgeModule.h>#import “C_to_RN.h”

Go back to the react native app, open the App.js file and write some code to get the input from users and a button to run the function.

// App.jsimport React, {useState} from 'react';
import {StyleSheet, Text, View, TextInput, Alert} from 'react-native';
import {NativeModules, Button} from 'react-native';
const App = () => {
const [number, setNumber] = useState('');
const onPress = (num: any) => {
const {C_to_RN} = NativeModules;
if (parseInt(num)) {
C_to_RN.WrapFactorial(parseInt(num), (_err, res) => console.log(res));
} else {
Alert.alert('Please enter a digit');
}
};
return (
<View style={styles.container}>
<Text> Practice !</Text>
<TextInput
style={{width: '50%', height: 40, borderBottomColor: 'black'}}
onChangeText={e => setNumber(e)}
value={number}
placeholder={'Input here'}
/>
<Button
title="C to React Native"
color="#841584"
onPress={() => onPress(number)}
/>
</View>
);
};
const styles = StyleSheet.create({
container: {
flex: 1,
justifyContent: 'center',
alignItems: 'center',
},
});
export default App;
1*OxbY8

And we are done, let’s run our application and see the result:

1*EKu26IVZnT Fv 3qnaGZSA

Finally, thank you for reading my article.



News Credit

%d bloggers like this: