15
3

More than 1 year has passed since last update.

Rustで書いたライブラリをC言語で使う

Posted at

これはなに

Rustの勉強をしていて、Rustで書いたライブラリをCで使ってみたいと思い、簡単なサンプルをつくったので記事にする。

何をやるのか

Rustで共有ライブラリを作成し、C言語で書いたコードのコンパイル時にリンクをする。
今回つくるのは、与えられた2つの引数の足し算・引き算をする関数。

手順

Rustで共有ライブラリをつくる

Rustのライブラリプロジェクトを作成する。

$ cargo new --lib c_with_rust

Cargo.tomlにライブラリターゲットをcdylibに指定する。

Cargo.toml
[package]
name = "c_with_rust"
version = "0.1.0"
edition = "2021"

+[lib]
+name = "c_with_rust"
+crate-type = ["cdylib"]

# See more keys and their definitions at https://doc.rust-lang.org/cargo/reference/manifest.html

[dependencies]

lib.rs#[no_mangle]pub extern "C"をつけ、add/sub関数を定義する。

lib.rs
#[no_mangle]
pub extern "C" fn add(x: i32, y: i32) -> i32 {
    x + y
}

#[no_mangle]
pub extern "C" fn sub(x: i32, y: i32) -> i32 {
    x - y
}

これで、cargo buildをすると、target/debug配下に共有ライブラリが作成される。

C言語でつくった共有ライブラリを使う

Rustで定義した関数のプロトタイプ宣言を含め、main.cを用意する。

main.c
#include <stdio.h>

int add(int x, int y);
int sub(int x, int y);

int main() {
  int x = 3;
  int y = 2;

  printf("add: %d\n", add(x, y));
  printf("sub: %d\n", sub(x, y));

  return 0;
}

コンパイルをする。

$ gcc main.o -L./target/debug -lc_with_rust -o main

実行して動作を確認。

$ ./main

add: 5
sub: 1

さいごに

C→Rustはなんとなくわかってきたが、Rust→Cがわからない...

Refs

15
3
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
15
3