Giter Site home page Giter Site logo

giuseppe998e / rust-ffi-example Goto Github PK

View Code? Open in Web Editor NEW
1.0 1.0 0.0 25 KB

An example of how to use a dynamic or static library created with the Rust language in a program written in the C language (FFI)

License: MIT License

C 57.56% Rust 42.44%
c rust cargo dynamic dynamic-library linking cbindgen example library rust-library

rust-ffi-example's Introduction

Requirements

  1. rust (with cargo)
  2. gcc
  3. cbindgen

Compile the Rust library

$ cd testlib
$ cargo build --release
$ cbindgen --crate testlib --lang c --output ../testlib.h
$ cp target/release/libtestlib.{so,a} ..

Compile the C executable

Using the dynamic lib

$ gcc example.c -L. -ltestlib -o example.out

Using the static lib

$ gcc example.c libtestlib.a -ldl -pthread -o example.out

Execute

$ chmod +x example.out
$ LD_LIBRARY_PATH=. ./example.out

N.B. The environment variable LD_LIBRARY_PATH is only needed for the dynamic version of the library.


The Rust (dynamic) library could also be loaded at runtime using the dlfcn.h library.
This repository does not offer an example for this alternative.

Useful links

  1. FFI - Wikipedia
  2. FFI - Rustonomicon
  3. A little Rust with your C
  4. Exposing FFI from the Rust library
  5. Creating a shared and static library with gcc
  6. Minimizing Rust Binary Size
  7. CBindGen Quick Start

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    ๐Ÿ–– Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. ๐Ÿ“Š๐Ÿ“ˆ๐ŸŽ‰

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google โค๏ธ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.