C++调用Rust

C++调用Rust

准备

使用官方提供的安装命令即可curl --proto '=https' --tlsv1.2 -sSf https://sh.rustup.rs | sh

开发

build.rs

fn main() {
    cxx_build::bridge("src/lib.rs")
        .file("src/rust_bridge.cpp")
        .flag_if_supported("-std=c++11")
        .compile("rust_bridge");
        println!("cargo:rerun-if-changed=src/lib.rs");
        println!("cargo:rerun-if-changed=src/rust_bridge.h");
        println!("cargo:rerun-if-changed=src/rust_bridge.cpp");
}

src/lib.rs

#[cxx::bridge]
mod ffi {
    extern "Rust" {
        fn cpp_call_rust();
    }
    unsafe extern "C++" {
        include!("helloworld/src/rust_bridge.h");
        fn rust_call_cpp();
    }
}

fn cpp_call_rust() {
    println!("call from c++");
}

fn test_rust() {
    ffi::rust_call_cpp();
}

cargo.toml

[package]
name = "helloworld"
version = "0.1.0"
edition = "2021"

[dependencies]
obfstr = "*"
litcrypt = "*"
cxx = "*"

[build-dependencies]
cxx-build = "*"

[lib]
crate-type = ["staticlib"]

src/rust_bridge.h

#pragma once
#include "rust/cxx.h"

void rust_call_cpp();

src/rust_bridge.cpp

#include "rust_bridge.h"
#include "helloworld/src/main.rs.h"

#include <stdio.h>

void rust_call_cpp() {
    printf("rust_call_cpp\n");
}

执行编译到iOS,得到文件target/aarch64-apple-ios/release/libhelloworld.a

cargo build --target aarch64-apple-ios --release

此时将libhelloworld.a/librs.h/librs.cc/cxx.h链接到XCode项目中即可调用cpp_call_rust函数!!!

iOS远程调试Rust

launch.json

{
    "version": "0.2.0",
    "configurations": [
        {
            "name": "Debug",
            "type": "lldb",
            "request": "custom",
            "initCommands": [
                "platform select remote-ios",
                "target create \"${workspaceFolder}/target/aarch64-apple-ios/debug/helloworld\"",
                "script lldb.debugger.GetSelectedTarget().modules[0].SetPlatformFileSpec(lldb.SBFileSpec(\"/usr/bin/helloworld\"))"
            ],
            "processCreateCommands": [
                "shell bash deploy.sh",
                "process connect connect://127.0.0.1:111",
                "run"
            ]
        }
    ]
}

deploy.sh

#!/bin/sh
ldid -Starget.plist target/aarch64-apple-ios/debug/helloworld
ssh [email]root@127.0.0.1[/email] "rm -f /usr/bin/helloworld"
scp target/aarch64-apple-ios/debug/helloworld [email]root@127.0.0.1[/email]:/usr/bin/

target.plist

<!DOCTYPE plist PUBLIC "-//Apple//DTD PLIST 1.0//EN http://www.apple.com/DTDs/PropertyList-1.0.dtd">
<plist version="1.0">
<dict>
	<key>platform-application</key>
	<true/>
</dict>
</plist>