상세 컨텐츠

본문 제목

Windows 에서 Rust 와 C/C++ 연동시 한글 처리

code/rust

by goldtagworks 2023. 11. 9. 11:59

본문

반응형

서버에서 실행될 프로그램을 만든다면 한글에 대해 별로 고민할 거리가 별로 없지만

클라이언트에서 실행되는 프로그램의 경우 한글이나 기타 언어들은 고민할 거리가 많습니다.

아무래도 컴퓨터 자체가 서구권에서 시작한것과 어떻게든 메모리와 데이터를 아껴야했던

당시 상황으로 써는 당연한 결과가 아닐까 싶네요.

 

뭐 여기까지 찾아 들어오신걸 보면 이미 많은 정보를 찾아보셨을꺼라 보고 핵심 부분만 코드로 남겨두겠습니다.

 

1. encoding_rs 라는 모듈을 이용한 방법입니다. 아래 명령으로 설치하시면 됩니다.

cargo add encoding_rs

 

테스트 코드 입니다. 주의할 점은 C/C++에서는 문자열이 null 로 끝나기 때문에 null 추가해줘야합니다.

pub fn string_encoding_rs(fullpath: String) -> bool {
    println!("rust(utf8) input: {:?}", fullpath);

    let (string_cow, _, _) = encoding_rs::EUC_KR.encode(&fullpath[..]);
    let mut c_fullpath = string_cow.to_vec();
    // C++ 은 null 문자열로 끝나기 때문에
    c_fullpath.push(0);

    // 출력
    println!("encoding_rs convert: {:?}", c_fullpath);

    unsafe {
        return call_string_test1(c_fullpath.as_ptr() as *const i8);
    }
}

 

2. widestring 라는 모듈을 이용한 방법입니다. 아래 명령으로 설치하시면 됩니다.

cargo add widestring

 

테스트 코드입니다. U16CString 라는 네이밍에서 보이듯 C에서 사용하는 null 스트링 입니다.

pub fn string_wstring(fullpath: String) -> bool {
    println!("rust(utf8) input: {:?}", fullpath);

    let c_fullpath = U16CString::from_str(fullpath).unwrap();

    // 출력
    println!("rust(null string) convert: {:#04x?}", c_fullpath);

    unsafe {
        return melon_string_test3(c_fullpath.as_ptr());
    }
}

 

개인적으로 null 처리가 따로 필요없는 widestring 를 추천합니다.

반응형