PHP code example of kingbes / phpc

1. Go to this page and download the library: Download kingbes/phpc library. Choose the download type require.

2. Extract the ZIP file and open the index.php.

3. Add this code to the index.php.
    
        
<?php
require_once('vendor/autoload.php');

/* Start to develop here. Best regards https://php-download.com/ */

    

kingbes / phpc example snippets



Kingbes\Phpc\Library;
use Kingbes\Phpc\CData;
use Kingbes\Phpc\SafeCall;
use Kingbes\Phpc\Memory;

$ffi = Library::load('libc', 'int strlen(const char*); void* malloc(size_t); void free(void*);');

// 用 CData::owned 包装 malloc 返回的指针,析构自动 FFI::free
$buf = $ffi->malloc(16);
$wrapped = CData::owned($buf);

// 安全地填充 C 字符串
Memory::copy($wrapped->raw(), 'hello', 5);
$wrapped->raw()[5] = "\0";

// 安全调用 strlen
$len = SafeCall::invoke($ffi, 'strlen', [$wrapped->raw()]);
echo $len; // 5

// 即使忘记 release,析构也会自动 free
$wrapped->release();

use Kingbes\Phpc\Phpc;

$ffi = Phpc::load('libc', 'int strlen(const char*);');
echo Phpc::call($ffi, 'strlen', [Phpc::toString('hello')]);

use Kingbes\Phpc\Exception\SafetyException;

try {
    // 任意 Phpc 调用
} catch (SafetyException $e) {
    // 统一处理
}
bash
php -d ffi.enable=true -f tests/run_examples.php