Created
July 15, 2023 06:11
-
-
Save SunKing2/40b5795e2a1ce9822368711627f68187 to your computer and use it in GitHub Desktop.
Run Rust from Perl (and from C)
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
set -e | |
cat > prime.rs <<EOF | |
#[no_mangle] | |
pub extern "C" fn is_prime(n: u64) -> bool { | |
if n <= 1 { | |
return false; | |
} | |
// check if even | |
if n % 2 == 0 { | |
return n == 2; | |
} | |
if n == 9 { | |
return false; | |
} | |
true | |
} | |
EOF | |
rustc prime.rs -O --crate-type cdylib | |
export LD_LIBRARY_PATH=. | |
cat > main.c <<EOF | |
#include <stdio.h> | |
extern int is_prime(unsigned int n); | |
int main() { | |
unsigned int n; | |
for (n = 0; n < 10; n++) { | |
printf("%d %s prime\n", n, is_prime(n) ? "is" : "is not"); | |
} | |
return 0; | |
} | |
EOF | |
gcc main.c -L. -lprime | |
./a.out | |
cat >run_prime.pl <<EOF | |
use v5.36; | |
use FFI::Platypus 2.00; | |
use FFI::CheckLib qw( find_lib_or_die ); | |
use File::Basename qw( dirname ); | |
my \$ffi = FFI::Platypus->new( api => 2, lib => './libprime.so' ); | |
\$ffi->attach( is_prime => ['int'] => 'bool' ); | |
say "\n\nHi I'm perl"; | |
say is_prime(7) ? "7 is prime" : "7 is not prime"; | |
say is_prime(8) ? "8 is prime" : "8 is not prime"; | |
say "done that 2"; | |
EOF | |
perl run_prime.pl |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment