프로그래밍과 잡담

Rust dll을 다른 언어에서 사용하기 (FFI) 본문

프로그래밍/Rust

Rust dll을 다른 언어에서 사용하기 (FFI)

크레온 2019. 10. 24. 22:08

Rust 언어는 프로그래머가 일일이 메모리 관리에 골머리를 쌓으면서 처리 안해도 돼는 좋은 언어이다.

게다가 성능도 C++와 비슷하거나 빠르다. 하지만 이 좋은 기능을 Rust 에서만 사용해서는 안됀다.  C언어나 C++ 처럼 다른 언어에서도 사용 할 수 있어야, 그 언어의 진가가 발휘 할 수 있을 것이다.  왜냐 일반적으로 가비지 컬렉션을 사용하는 자바나 C# 또는 인터프리터 언어들(python, ruby 등등등)은 바이너리 언어 비해서 성능이 떨어지는 편이다.  요즘은 많이 좋아졌다고는 하지만 1분 1초가 중요하게 생각하는 분야에서는 여전히 C/C++이 대세이다.

 

당연하게도 rust에서는 이 기능을 제공하고 있다.

 

콘솔을 열고 아래와 비슷한 rust 프로젝트를 생성한다.
$cargo new myfunc

그리고 Cargo.toml을 열고 아래의 코드를 추가한다.

[lib]
name = "libmyfunc"
crate-type = ["dylib"]

 

 lib.rs 파일을 생성한다.

그리고 대충 인터넷에서 뒤져서 rust 코드로 만든다.

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

#[no_mangle]
pub extern fn fibonacci(x: i32) -> i32 {
    if x == 0 { return 0; }
    else if x == 1 { return 1; }
    else { return fibonacci(x-1) + fibonacci(x-2); }
}

#[no_mangle]
pub extern fn hello_world () {
    println!("Hello World ~!!");

}

그리고 콘솔에서 아래의 코드를 입력한다

$ cargo build --release

릴리즈 모드로 빌드하는 것이다.

 

target/release 폴더에 들어가면 dll이 있다,

 

그걸 다른 언어에서 사용하면 된다.

 

난 주로 C#을 사용하기 때문에 C#의 예제를 올려보겠다.

 

using System;
using System.Collections.Generic;
using System.Runtime.InteropServices;
using System.Text;

namespace Rust_FFI
{
    class FFI
    {
        // C#에서 FFI (Foreign Function Interface )는 이렇게만 사용하면 됨.
        
        [DllImport("libmyfunc.dll", EntryPoint = "hello_world")]
        public static extern void hello_world();

        [DllImport("libmyfunc.dll", EntryPoint = "add")]
        public static extern int add(int x, int y);

        [DllImport("libmyfunc.dll", EntryPoint = "fibonacci")]
        public static extern int fibonacci(int x);

        public FFI()
        {
            Console.WriteLine("Rust Library를 로드 하고 테스트");
        }

        public void testHello_World()
        {
            hello_world();
        }

        public void testAdd()
        {
            Console.WriteLine($"10 + 20 = {add(10, 20)}");

            Console.WriteLine($"30 + 40 = {add(30, 40)}");
        }


        public void testFibonacci()
        {
            Console.WriteLine("피보나치 테스트");
            for (int i = 0; i < 11; i++)
            {
                Console.Write($"{fibonacci(i)}  ");
            }

        }


    }
}

 

위 처럼 사용하면 끝임.

 

아래는 실행한 결과 스크린샷

 

코드 보면 알겠지만 매우 간단하게 다른 언어에서 Rust에서 만든 기능을 사용 할 수 있다.

당연하지만 Rust는 unsafe 블락을 이용하지 않는 이상 메모리 오류가 발생하지 않는다. 

물론, 잘못된 코드로 인한 문제는 못 잡는다 ㅋ 

 

 

 

참조 사이트 : https://doc.rust-lang.org/1.5.0/book/rust-inside-other-languages.html

 

Rust Inside Other Languages

Rust Inside Other Languages For our third project, we’re going to choose something that shows off one of Rust’s greatest strengths: a lack of a substantial runtime. As organizations grow, they increasingly rely on a multitude of programming languages. Diff

doc.rust-lang.org

 

반응형
Comments