chore: reorg

This commit is contained in:
2020-10-17 11:47:07 +08:00
parent 9d4d830115
commit a034988643
56 changed files with 13431 additions and 0 deletions

16
__c_cpp/c_export/Cargo.lock generated Normal file
View File

@@ -0,0 +1,16 @@
# This file is automatically @generated by Cargo.
# It is not intended for manual editing.
[[package]]
name = "c_export"
version = "0.1.0"
dependencies = [
"libc 0.2.60 (registry+https://github.com/rust-lang/crates.io-index)",
]
[[package]]
name = "libc"
version = "0.2.60"
source = "registry+https://github.com/rust-lang/crates.io-index"
[metadata]
"checksum libc 0.2.60 (registry+https://github.com/rust-lang/crates.io-index)" = "d44e80633f007889c7eff624b709ab43c92d708caad982295768a7b13ca3b5eb"

View File

@@ -0,0 +1,14 @@
[package]
name = "c_export"
version = "0.1.0"
authors = ["Hatter Jiang <jht5945@gmail.com>"]
edition = "2018"
# See more keys and their definitions at https://doc.rust-lang.org/cargo/reference/manifest.html
[lib]
name = "stringtools"
crate-type = ["dylib"]
[dependencies]
libc = "0.2.60"

View File

@@ -0,0 +1,29 @@
Rust libray build:
```
cargo build
```
Python test:
```
python call_in_python.py
```
C test:
```
gcc call_in_c.c -L target/debug/ -lstringtools
```
NodeJS test:
```
npm install ffi
node call_in_node.js
```
Reference:
http://siciarz.net/24-days-of-rust-calling-rust-from-other-languages/

View File

@@ -0,0 +1,9 @@
#include <stdint.h>
#include <stdio.h>
int32_t count_substrings(const char* value, const char* substr);
int main() {
printf("%d\n", count_substrings("banana", "na"));
return 0;
}

View File

@@ -0,0 +1,8 @@
var ffi = require('ffi');
var stringtools = ffi.Library('target/debug/libstringtools.dylib', {
'count_substrings': ['int', ['string', 'string']]
});
console.log(stringtools.count_substrings("banana", "na"));

View File

@@ -0,0 +1,5 @@
import ctypes
stringtools = ctypes.CDLL("target/debug/libstringtools.dylib")
print(stringtools.count_substrings(b"banana", b"na"))

View File

@@ -0,0 +1,17 @@
extern crate libc;
use std::ffi::CStr;
use libc::c_char;
#[no_mangle]
pub extern "C" fn count_substrings(value: *const c_char, substr: *const c_char) -> i32 {
let c_value = unsafe { CStr::from_ptr(value) };
let c_substr = unsafe { CStr::from_ptr(substr) };
match c_value.to_str() {
Ok(value) => match c_substr.to_str() {
Ok(substr) => value.match_indices(substr).count() as i32,
Err(_) => -1,
},
Err(_) => -1,
}
}