跳转到主要内容
CString 包装一个原始 C 字符串指针(const char*)并提供安全读取。

示例

import { dlopen, FFIType, CString } from 'arkffi';

const lib = dlopen('libffi_target.so', {
  getVersion: { args: [], returns: FFIType.int64 },
});

const ptr: number = lib.symbols.getVersion();
const cstr = new CString(ptr);

cstr.toString(); // → "1.0.0"
cstr.length;     // → 5

lib.close();

构造函数

constructor(ptr: number, byteOffset?: number, byteLength?: number);
参数类型默认值说明
ptrnumberC 字符串的内存地址
byteOffsetnumber0跳过前 N 个字节再开始读取
byteLengthnumber自动检测 null 结尾显式指定读取长度
从原始内存地址创建 CString。指针必须指向有效的 C 字符串。可选地指定偏移量和长度。
const cstr = new CString(ptr, 0, 5);
cstr.toString(); // 读取前 5 个字节

属性

length

get length(): number;
返回 C 字符串的长度(字符数)。

方法

toString()

toString(): string;
读取 C 字符串并以 ArkTS 字符串返回。

空指针

传入 0(空指针)是安全的,返回空字符串:
const cstr = new CString(0);
cstr.toString(); // → ""
cstr.length;     // → 0