Add String Conversion Function

This commit is contained in:
GuilhermeWerner
2021-04-18 20:15:00 -03:00
parent 293aef9dbf
commit d51196ff4b
7 changed files with 75 additions and 0 deletions

View File

@ -4,6 +4,16 @@
int main()
{
// Hello
char *result = Hello("C");
printf("%s\n", result);
DeallocString(result);
// Operations
int num1 = 1;
int num2 = 2;

View File

@ -11,6 +11,9 @@ namespace CSharp
const string Library = "libLibrary";
#endif
[DllImport(Library)]
static extern string Hello(string input);
[DllImport(Library)]
static extern float Add(float Num1, float Num2);
@ -25,6 +28,14 @@ namespace CSharp
static void Main(string[] args)
{
// Hello
string result = Hello("C#");
Console.WriteLine(result);
// Operations
int num1 = 1;
int num2 = 2;

View File

@ -6,6 +6,15 @@ using namespace std;
int main()
{
// Hello
char *result = Library::Hello("C++");
cout << result << "\n";
Library::DeallocString(result);
// Operations
int num1 = 1;
int num2 = 2;

12
Source/Allocator.rs Normal file
View File

@ -0,0 +1,12 @@
use libc::c_char;
use std::ffi::CString;
#[no_mangle]
/// Dealloc a string pointer.
pub extern "C" fn DeallocString(ptr: *mut c_char) {
if ptr.is_null() {
return;
}
unsafe { CString::from_raw(ptr) };
}

14
Source/Converter.rs Normal file
View File

@ -0,0 +1,14 @@
use libc::c_char;
use std::ffi::{CStr, CString};
/// Convert C string to Rust String.
pub fn ToString(ptr: *mut c_char) -> String {
let input = unsafe { CStr::from_ptr(ptr) };
return input.to_str().unwrap().to_string();
}
/// Convert Rust String to C string.
pub fn FromString(string: String) -> *mut c_char {
return CString::new(string).unwrap().into_raw();
}

View File

@ -18,8 +18,15 @@ namespace Library
float Add(float num1, float num2);
/**
* Dealloc a string pointer.
*/
void DeallocString(char *ptr);
float Divide(float num1, float num2);
char *Hello(char *input);
float Multiply(float num1, float num2);
float Subtract(float num1, float num2);

View File

@ -1,5 +1,17 @@
#![allow(non_snake_case)]
mod Allocator;
mod Converter;
use libc::c_char;
#[no_mangle]
pub extern "C" fn Hello(input: *mut c_char) -> *mut c_char {
let output = format!("Hello {}", Converter::ToString(input));
return Converter::FromString(output);
}
#[no_mangle]
pub extern "C" fn Add(num1: f32, num2: f32) -> f32 {
return num1 + num2;