1个不稳定版本

0.10.1 2023年8月27日

#5#zend


用于 nicelocal-ext-php-rs

MIT/Apache

99KB
2.5K SLoC

ext-php-rs

Crates.io docs.rs Guide Workflow Status CI Workflow Status Discord

为构建Rust原生PHP扩展而提供的Zend API绑定和抽象。

示例

将一个简单的函数 function hello_world(string $name): string 导出为PHP

#![cfg_attr(windows, feature(abi_vectorcall))]

use nicelocal_ext_php_rs::prelude::*;

/// Gives you a nice greeting!
/// 
/// @param string $name Your name.
/// 
/// @return string Nice greeting!
#[php_function]
pub fn hello_world(name: String) -> String {
    format!("Hello, {}!", name)
}

// Required to register the extension with PHP.
#[php_module]
pub fn module(module: ModuleBuilder) -> ModuleBuilder {
    module
}

使用 cargo-php 构建IDE存根并安装扩展

$ cargo install cargo-php
  Installing cargo-php v0.1.0
$ cargo php stubs --stdout
  Compiling example-ext v0.1.0
  Finished dev [unoptimized + debuginfo] target(s) in 3.57s
<?php

// Stubs for example-ext

/**
 * Gives you a nice greeting!
 *
 * @param string $name Your name.
 *
 * @return string Nice greeting!
 */
function hello_world(string $name): string {}
$ cargo php install --release
  Compiling example-ext v0.1.0
  Finished release [optimized] target(s) in 1.68s
Are you sure you want to install the extension `example-ext`? yes
$ php -m
[PHP Modules]
// ...
example-ext
// ...

从PHP调用函数

var_dump(hello_world("David")); // string(13) "Hello, David!"

更多示例请参阅库 指南

特性

  • 易于使用: 内置的宏可以抽象出与Zend API交互的需要,例如Rust类型函数参数抽象出与Zend值交互。
  • 轻量级: 您不必使用内置的辅助宏。可以围绕自己的函数编写自己的粘合代码。
  • 可扩展: 为您的自定义类型实现 IntoZvalFromZval,允许类型作为函数参数和返回类型使用。

目标

我们的主要目标是 使扩展开发更加容易。

  • 用C编写扩展可能会很繁琐,而且Zend API有限的文档可能会令人畏惧。
  • Rust的现代语言功能和功能丰富的标准库是C的巨大改进。
  • 抽象原始Zend API可以加快扩展的开发速度并提高信心。
  • 抽象还允许我们支持未来(以及可能过去的)PHP版本,而无需对扩展代码进行重大更改。

文档

库指南可以在此处阅读:这里

该项目以行内形式进行了文档编写,因此目前最好的资源是查看 cargo 文档。这可以在 docs.rs 上查看。

需求

  • 基于Linux、macOS或Windows的操作系统。
  • PHP 8.0或更高版本。
    • 不计划支持PHP的早期版本。
  • Rust。
    • 目前,我们不保证MSRV,然而在编写时,lib.rs建议使用Rust 1.57。
  • Clang 5.0或更高版本。

Windows需求

  • 只能为来自https://windows.php.net的PHP安装编译扩展。最终计划支持其他安装。
  • Windows需要Rust nightly。这是由于某些PHP函数在Windows上使用vectorcall调用约定,这仅在Rust的nightly不稳定功能中可用。
  • 建议使用rust-lld链接器来链接您的扩展。虽然支持MSVC链接器(link.exe),但如果链接器版本不被您的PHP安装支持,您可能会遇到问题。您可以通过创建一个包含以下内容的.cargo\config.toml文件来使用rust-lld链接器:
    # Replace target triple if you have a different architecture than x86_64
    [target.x86_64-pc-windows-msvc]
    linker = "rust-lld"
    
  • cc crate需要系统上存在cl.exe。这通常包含在Microsoft Visual Studio中。
  • cargo-php的存根生成功能在Windows上不起作用。将此功能重写为跨平台功能已在路线图上。

Cargo功能

默认情况下,所有功能都未启用。

  • closure - 启用将Rust闭包返回到PHP的能力。创建了一个新的类类型,RustClosure
  • anyhow - 为anyhow::Error实现Into<PhpException>,允许您从PHP函数返回anyhow结果。支持anyhow v1.x。

用法

查看以下示例项目之一

贡献

非常欢迎贡献。我是一个Rust开发者新手,任何建议都欢迎。请通过Github提交问题和PR。

欢迎的贡献包括

  • 文档扩展(特别是示例!)
  • 安全审查(特别是如果您有Rust和Zend API的经验)。
  • 错误修复和功能。
  • 功能请求。

除非您明确说明,否则您提交给工作以包含在内的任何贡献,根据Apache-2.0许可证的定义,应如上所述双重许可,不附加任何其他条款或条件。

资源

许可证

以下任一许可证下授权:

任选其一。

依赖关系

~2MB
~45K SLoC