Skip to content

Instantly share code, notes, and snippets.

@kassane
Last active August 11, 2019 20:10
Show Gist options
  • Save kassane/8b71ed122e235d7413976d08c3c5513a to your computer and use it in GitHub Desktop.
Save kassane/8b71ed122e235d7413976d08c3c5513a to your computer and use it in GitHub Desktop.
DynamicLibrary in Rust to Others Languages - FFI
[package]
name = "cs_call_rst"
version = "0.1.0"
[lib]
name="fib_rust"
crate-type = ["cdylib"]
[dependencies]
#include <cstdint>
template<typename T> T fib(T n)
{
return n > 1 ? fib(n - 1) + fib(n - 2) : 1;
}
template uint64_t fib<uint64_t>(uint64_t);
//GCC command: g++ -Wall -O3 -c -fPIC fib_dll.cpp && g++ -shared -o fib_cpp.dll fib_cpp.o
#[no_mangle] //mantém o nome da função de forma externa
pub extern fn fib2(n: u64) -> u64 {
if n > 1
{
return fib(n - 1) + fib(n - 2);
}
1
}
#include <iostream>
#include <thread>
#include <mutex>
#include <chrono>
#include <cstdint>
std::mutex m;
extern "C" uint64_t fib2(uint64_t n); //rust
uint64_t fib(uint64_t n); //C++
//GCC command: g++ -o Fib.exe -L. -lfib_mgw main.cpp
auto main() -> int
{
std::thread t1([]{
std::lock_guard<std::mutex>lr(m);
auto start = std::chrono::system_clock::now();
std::cout << "Rust Library:\n\n";
for(auto i=0; i < 41; ++i) std::cout << "Rust -> " << i << " : " << fib2(i) << std::endl;
std::cout << "\nTime Elapsed: " << std::chrono::duration_cast<std::chrono::milliseconds>(std::chrono::system_clock::now() - start).count() << " ms\n";
}),
t2([]{
std::lock_guard<std::mutex>lr(m);
auto start = std::chrono::system_clock::now();
std::cout << "================================\nC++ Library:\n\n";
for(auto i=0; i < 41; ++i) std::cout << "C++ -> " << i << " : " << fib(i) << std::endl;
std::cout << "\nTime Elapsed: " << std::chrono::duration_cast<std::chrono::milliseconds>(std::chrono::system_clock::now() - start).count() << " ms\n";
});
t1.join();
t2.join();
}
//more info: https://www.reddit.com/r/metapcj/comments/8uz5hi/self_meta_jerk_in_fact_rust_structs_are_just/
program Estudos;
uses sysutils, dynlibs;
procedure UseDLL;
type
TMyFunc=function (n:Integer):Integer; StdCall;
var
MyLibC: TLibHandle = dynlibs.NilHandle;
MyFunc: TMyFunc;
FuncResult: integer;
begin
MyLibC := LoadLibrary('fib_rust.' + SharedSuffix);
if MyLibC = dynlibs.NilHandle then Exit; //DLL was not loaded successfully
MyFunc:= TMyFunc(GetProcedureAddress(MyLibC, 'fib'));
FuncResult:= MyFunc (5); //Executes the function
if MyLibC <> DynLibs.NilHandle then if FreeLibrary(MyLibC) then MyLibC:= DynLibs.NilHandle; //Unload the lib, if already loaded
writeln('Result fibonacci (Lib Rust): '+InttoStr(FuncResult));
end;
procedure Main;
begin
UseDLL;
end;
begin
Main;
end.
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment