1

подскажите как из Python вызывать Rust функцию которая возвращает строку, код:
Python

from ctypes import *
import ctypes

lib = cdll.LoadLibrary("embed/target/release/embed.dll")
lib.print_text("Hello, from python")

Rust

#[no_mangle]
pub extern fn print_text2(x: String) {
    println!("{}", x);
}

1 ответ 1

1

Подразумевая, что функция всё же принимает строку, а не возвращает и вызов производится через Сишные интерфейсы намеренно, то как-то так:

from ctypes import *
import ctypes

lib = cdll.LoadLibrary("embed/target/release/embed.dll")
lib.print_text("Hello, from python".encode())

Rust:

use std::os::raw::c_char;
use std::ffi::CStr;

#[no_mangle]
pub extern "C" fn print_text(x: *const c_char) {
    println!("Rust writes: {}", unsafe {CStr::from_ptr(x)}.to_str().unwrap());
}

Более простым способом интегрировать rust-код в python, пожалуй, будет создание python-модуля средствами PyO3


См. также:

Ваш ответ

By clicking “Отправить ответ”, you agree to our terms of service and acknowledge that you have read and understand our privacy policy and code of conduct.

Всё ещё ищете ответ? Посмотрите другие вопросы с метками или задайте свой вопрос.