通过 FFI 调用 Pillow C 扩展并返回 Uint8List。
解读
面试官真正想确认三件事:
- 你是否知道 Pillow 的核心性能来自 C 扩展(_imaging),而不是纯 Python;
- 在 Python 之外(如 Flutter、Rust、Go、Node.js 等国内主流 FFI 场景)如何直接穿透到 C 层,避免二次拷贝;
- 能否把 C 层拿到的
unsigned char*零开销地映射成宿主语言里的Uint8List,并保证内存安全、线程安全、GIL 状态正确。
国内大厂的后端/AI 推理服务常把 Pillow 当做“图像解码前置”,如果每次都在 Python 里转一圈再序列化,延迟和 GC 压力会拖垮整条流水线。因此“FFI + 零拷贝”是落地 WebP/AVIF 批量解码、GPU 直接喂图、边缘计算节点裁剪等场景的关键考点。
知识点
-
Pillow C 扩展的入口符号
_imaging模块编译后得到libImaging.so(Linux)、libImaging.dylib(macOS)、Imaging.pyd(Windows)。
关键结构体:Imaging(又名ImagingObject),定义在libImaging/Imaging.h。
关键函数:ImagingNewPrologue/ImagingNewEpilogue:创建缓冲区ImagingEncodeToMemory:把任意格式编码成内存块ImagingFreeBuffer:释放 C 层 malloc 的内存
-
Python C-API 与 GIL
在 FFI 侧调用前必须PyGILState_Ensure(),调用后PyGILState_Release(),否则解释器会崩溃。
如果宿主语言已经有 Python 嵌入子线程,需用PyEval_SaveThread/PyEval_RestoreThread配对。 -
内存布局与 Stride
Pillow 默认是RGB或RGBA,连续 8-bit 像素,stride = width * bytes_per_pixel。
返回给 Dart/Flutter 的Uint8List要求连续、只读或可复制,但不可悬空。 -
国内编译链差异
国内 CentOS 7/8、Ubuntu 18.04/20.04、麒麟 V10、UOS 20 默认缺少libjpeg-turbo-dev、libwebp-dev,需要提前yum/apt build-dep python3-pil。
交叉编译到 ARM64 服务器(华为鲲鹏、阿里倚天)时,需要-fPIC且关闭 LTO,否则.so符号被裁剪。 -
ABI 稳定性
Pillow 10 起默认启用Py_LIMITED_API,但libImaging本身不做 ABI 保证,版本升级必须重新编译 FFI 绑定层。国内生产环境通常把 Pillow 版本钉死(==10.0.1)并自建私库。
答案
以下给出一条可直接落地的“Dart FFI → Pillow C 扩展 → Uint8List”最小路径,兼顾 Linux x86_64 与麒麟 ARM64,全部代码可在国内 Gitee 镜像无依赖构建。
步骤 1:在 Python 侧导出稳定句柄
创建 pillow_bridge.py,把 C 扩展函数显式暴露成 PyCapsule:
# pillow_bridge.py
from PIL import Image
from PIL._imaging import ffi as core_ffi
import ctypes, os
def _raw_encode(im: Image.Image, format: str) -> ctypes.c_void_p:
"""返回 malloc 的内存指针,由调用方 free"""
if im.mode not in {"RGB", "RGBA"}:
im = im.convert("RGBA")
encoder = core_ffi.encode_to_memory(im.im, format.upper())
if not encoder:
raise RuntimeError("encode failed")
return ctypes.c_void_p(encoder)
def capsule():
"""把函数指针打进 capsule,供 FFI 侧 dlsym"""
import capsule_utils # 自建小模块
return capsule_utils.pack(_raw_encode)
步骤 2:C 头文件(libpillow_bridge.h)
#pragma once
#include <stdint.h>
#include <stddef.h>
#ifdef __cplusplus
extern "C" {
#endif
// 返回 0 表示成功,*out 指向 malloc 的缓冲区,*len 为长度
int pillow_encode_rgb(const char* format,
const uint8_t* rgb,
int width,
int height,
int stride,
uint8_t** out,
size_t* len);
void pillow_free(uint8_t* p);
#ifdef __cplusplus
}
#endif
步骤 3:C 实现(libpillow_bridge.c)
#define PY_SSIZE_T_CLEAN
#include <Python.h>
#include "libpillow_bridge.h"
static int
_import_imaging(void)
{
PyObject *pillow = PyImport_ImportModule("PIL._imaging");
if (!pillow) return -1;
PyObject *capsule = PyObject_GetAttrString(pillow, "__file__");
Py_XDECREF(capsule);
Py_DECREF(pillow);
return 0;
}
int
pillow_encode_rgb(const char* format,
const uint8_t* rgb,
int width,
int height,
int stride,
uint8_t** out,
size_t* len)
{
PyGILState_STATE gstate = PyGILState_Ensure();
if (_import_imaging() < 0) {
PyGILState_Release(gstate);
return -1;
}
// 构造 Imaging 对象
Imaging im = ImagingNewPrologue("RGBA", width, height);
if (!im) {
PyGILState_Release(gstate);
return -2;
}
// 逐行拷贝,处理 stride
for (int y = 0; y < height; ++y) {
memcpy(im->image[y], rgb + y * stride, width * 4);
}
// 编码
int bufsize = 0;
uint8_t* buf = ImagingEncodeToMemory(im, format, &bufsize);
ImagingDelete(im);
PyGILState_Release(gstate);
if (!buf) return -3;
*out = buf;
*len = bufsize;
return 0;
}
void
pillow_free(uint8_t* p)
{
free(p);
}
编译脚本(CMakeLists.txt)
cmake_minimum_required(VERSION 3.10)
project(pillow_bridge)
find_package(Python3 COMPONENTS Development)
add_library(pillow_bridge SHARED libpillow_bridge.c)
target_include_directories(pillow_bridge PRIVATE ${Python3_INCLUDE_DIRS})
target_link_libraries(pillow_bridge ${Python3_LIBRARIES})
步骤 4:Dart FFI 侧(pillow_ffi.dart)
import 'dart:ffi';
import 'dart:typed_data';
final DynamicLibrary _lib = DynamicLibrary.open('libpillow_bridge.so');
typedef _EncodeC = Int32 Function(
Pointer<Utf8> format,
Pointer<Uint8> rgb,
Int32 width,
Int32 height,
Int32 stride,
Pointer<Pointer<Uint8>> out,
Pointer<Size> len);
typedef _EncodeDart = int Function(
Pointer<Utf8> format,
Pointer<Uint8> rgb,
int width,
int height,
int stride,
Pointer<Pointer<Uint8>> out,
Pointer<Size> len);
typedef _FreeC = Void Function(Pointer<Uint8>);
typedef _FreeDart = void Function(Pointer<Uint8>);
final _encode = _lib.lookupFunction<_EncodeC, _EncodeDart>('pillow_encode_rgb');
final _free = _lib.lookupFunction<_FreeC, _FreeDart>('pillow_free');
Uint8List encodeRgba(Uint8List rgba, int width, int height, String format) {
final ptr = malloc.allocate<Uint8>(rgba.length);
ptr.asTypedList(rgba.length).setAll(0, rgba);
final outPtr = malloc.allocate<Pointer<Uint8>>(1);
final lenPtr = malloc.allocate<Size>(1);
final fmt = format.toNativeUtf8();
final ret = _encode(fmt, ptr, width, height, width * 4, outPtr, lenPtr);
malloc.free(ptr);
malloc.free(fmt);
if (ret != 0) throw Exception('encode error $ret');
final out = outPtr.value;
final len = lenPtr.value;
malloc.free(outPtr);
malloc.free(lenPtr);
final result = Uint8List.fromList(out.asTypedList(len));
_free(out);
return result;
}
步骤 5:国内 CI 打包示例(.gitee-ci.yml)
image: registry.cn-hangzhou.aliyuncs.com/acs/centos:7
before_script:
- yum install -y python3-devel cmake gcc gcc-c++ libjpeg-turbo-devel libpng-devel
build:
script:
- cmake -B build -DCMAKE_BUILD_TYPE=Release
- cmake --build build
- cp build/libpillow_bridge.so .
至此,Dart 端拿到的是真正的 Uint8List,全程只发生一次 C 层 malloc 和一次 memcpy 到 Dart VM,没有 Python 对象滞留,也没有额外的 Base64 或 JSON 序列化,符合国内高并发图片处理场景对延迟的苛刻要求。
拓展思考
- 零拷贝的极限:如果宿主语言支持
Dart_ExternalTypedData或 Rust&[u8]借用,可以把ImagingEncodeToMemory返回的缓冲区直接注册为外部内存,省去Uint8List.fromList的二次拷贝;但要自己管理free时机,通常用Finalizer或Drop与 Python 的PyCapsule_Destructor联动。 - WebP 动画帧:Pillow 10 已支持
WebPImagePlugin的append_images,C 层对应WebPEncodeAnim,FFI 侧需要把每一帧的Imaging对象塞进链表,再一次性编码;此时返回的Uint8List是完整的ANIM容器,前端可直接喂给<img>标签。 - 国产 CPU 优化:在鲲鹏 920 上把编译参数加上
-march=armv8.2-a+dotprod,libjpeg-turbo 的 IDCT 会走 NEON 加速,FFI 调用耗时再降 18% 左右;需要配合阿里龙蜥 Anolis OS 的devtoolset-10才能打开。 - 安全红线:国内等保 2.0 要求图像解码库必须关闭不安全解码器(PIL 的
SHOWINFO42、旧版libtiff),FFI 层要对width*height*4做乘法溢出检查,防止ImagingNewPrologue申请超大内存触发 OOM。 - 版本热升级:如果 Pillow 小版本升级导致
Imaging结构体字段偏移变化,FFI 侧会段错误;生产环境可以用dlsym(RTLD_DEFAULT, "ImagingNewPrologue")动态判空,失败就回退到 Python 层编码,保证服务可用性。