כריכת Cairo מובנית, נשלחת#

פרק הווקטור צייר עם Cairo כמודול CPAN רגיל. פרק זה מראה את הצד השני של אותו קוד: pperl שולח מימוש מחדש מובנה של Cairo, כך ש־use Cairo עובד על pperl בלי הפצת Cairo של CPAN מותקנת ובלי מהדר C מעורב. ה־Perl שאתם כותבים זהה; מה שמגבה אותו הוא ה־FFI של pperl עצמו המגיע ל־libcairo ישירות. Cairo מהווה את הדוגמה המעובדת האידיאלית מפני שה־API של C שלו הוא כמעט כולו סקלרים וידית אטומה אחת, וזו בדיוק הצורה שמגיעה בנקיות היום.

This is a real, shipped binding, not a sketch. Reading it tells you what a native graphics binding is, how the pieces fit, and how to recognise (or ask for) the same treatment for another library. Building such a binding is a runtime task; what you write as a user is the Perl on the far side of it, and that Perl is just the Cairo API you already saw.

ה־API של Perl: בדיוק זה של CPAN#

הכריכה המובנית חושפת את שמות החבילות והמתודות האמיתיים של Cairo: Cairo::ImageSurface, Cairo::Context, Cairo::PdfSurface והשאר, עם חתימות המתודה של מעלה־הזרם. קוד שנכתב עבור Cairo של CPAN רץ ללא שינוי; חבילות בדיקה של Cairo שהוסבו עוברות מולו. התוכנית מפרק הווקטור היא התוכנית כאן:

use Cairo;

my $surface = Cairo::ImageSurface->create('argb32', 200, 200);
my $cr      = Cairo::Context->create($surface);

$cr->set_source_rgb(1, 1, 1);
$cr->paint;                                  # white background
$cr->set_source_rgb(0, 0, 0);
$cr->set_line_width(3);
$cr->move_to(20, 20);
$cr->line_to(180, 20);
$cr->stroke;
$cr->arc(100, 100, 40, 0, 6.28318);
$cr->set_source_rgba(1, 0, 0, 0.5);
$cr->fill;

$surface->write_to_png('out.png');
# the surface and context free their C objects when they go out of scope

שום דבר בתוכנית הזו אינו רומז כיצד היא ממומשת. אין dlopen, אין מחרוזת חתימה, אין אובייקט כריכה: רק Cairo. שאר הפרק הזה הוא מה שגורם ל־use Cairo לעשות זאת על pperl, והתבנית זהה לזו שמאחורי Math::GMP.

צעד 1: פתחו את הספרייה פעם אחת, פתרו את הסמלים#

The binding opens libcairo.so.2 a single time, when the module loads, and resolves each C function it needs into a table of function pointers held for the life of the process. Opening the library, the symbol table and the class each C pointer type is wrapped in come from Peta::FFI’s binding layer, which every native library binding in pperl is built on. This is the same shape as the Math::GMP binding, which opens libgmp once and resolves its mpz_* symbols. For Cairo the resolved symbols are the ones behind the methods above:

open libcairo.so.2 once when the module loads
resolve and store, as function pointers:
    cairo_image_surface_create(format, width, height) -> surface*
    cairo_create(surface*)                             -> context*
    cairo_move_to(context*, x, y)
    cairo_line_to(context*, x, y)
    cairo_arc(context*, xc, yc, radius, a1, a2)
    cairo_set_source_rgb(context*, r, g, b)
    cairo_set_source_rgba(context*, r, g, b, a)
    cairo_set_line_width(context*, w)
    cairo_stroke(context*)  cairo_fill(context*)  cairo_paint(context*)
    cairo_surface_write_to_png(surface*, path) -> status
    cairo_destroy(context*)  cairo_surface_destroy(surface*)

If libcairo is not installed on the system, use Cairo still succeeds, and the first call that needs the library dies with a message saying how to install it. If the installed libcairo is too old to have one of these functions, only the method that calls it dies, naming the C function; you can catch that with eval like any other error. Every one of those C functions has a signature the FFI’s type codes already express: the arguments are the opaque handle (an address, so an integer), doubles, and a string path. There is no by-value struct in the core drawing API, which is why Cairo is the clean example.

Cairo היא ספרייה גדולה, ולכן הכריכה האמיתית מאורגנת לפי חבילה: Cairo::Surface, Cairo::Context, Cairo::Path, Cairo::Pattern, Cairo::Matrix, Cairo::Font ו־Cairo::Region, כשכל אחת פותרת את הסמלים הדרושים לה. זו נוחות מימוש; המשתמש רואה Cairo אחד. לכל אחת מהחבילות האלה יש עמוד עזר משלה תחת Cairo, עם המתודות שהיא נושאת ועם מה שכל אחת מחזירה. כשאתם רוצים לחפש מתודה ולא להבין את התבנית, אותו עמוד עזר הוא המקום ללכת אליו, לא הפרק הזה.

צעד 2: הידית האטומה כמספר שלם מבורך#

Cairo מחזירה cairo_surface_t* ו־cairo_t*: מצביעים ל־structs של C שבפנימיותם לעולם אינכם נוגעים. הכריכה אינה צריכה להבין את הפריסה שלהם, רק להחזיק את המצביע ולהעביר אותו בחזרה בכל קריאה. pperl מייצג ידית כזו באותו אופן שMath::GMP מחזיק את מצביע ה־mpz_t שלו: כמספר שלם בתוך הפניה מבורכת.

Cairo::ImageSurface object  =  bless(\ (surface_ptr as integer), 'Cairo::ImageSurface')
Cairo::Context object       =  bless(\ (context_ptr as integer), 'Cairo::Context')

כשמתודה נקראת, הכריכה קוראת את המספר השלם בחזרה מתוך ההפניה המבורכת, ממירה אותו למצביע ה־C, וקוראת לפונקציה. הברכה נותנת לכם שיגור מתודות ($cr->stroke), הורשה (כל מחלקת משטח קונקרטית היא תת־מחלקה של Cairo::Surface), ובאופן מכריע, וו DESTROY. ההבדל היחיד מ־Math::GMP הוא שהדבר האטום הוא משטח ציור במקום מספר שלם גדול.

צעד 3: משך החיים קשור ל־DESTROY#

אובייקט גרפיקה של C חייב להשתחרר בדיוק פעם אחת. הדליפו אותו וכל ציור יעלה לכם זיכרון שלא תקבלו בחזרה לעולם; שחררו אותו פעמיים ותשחיתו את הזיכרון שהמקצה של C מנהל, מה שמקריס את התוכנית מאוחר יותר, במקום לא־קשור וקשה לאיתור. הכריכה קושרת את חיי אובייקט ה־C לאלה של אובייקט ה־Perl: כשההפניה המבורכת יוצאת מתחום, Perl קורא ל־DESTROY, והכריכה קוראת ל־destructor התואם של C, תוך כיבוד ספירת ההפניות של cairo.

Cairo::Context DESTROY  ->  cairo_destroy(context_ptr)
Cairo::Surface DESTROY  ->  cairo_surface_destroy(surface_ptr)

Math::GMP עושה בדיוק זאת: ה־destructor שלו קורא ל־mpz_clear ומשחרר את ה־mpz_t. אתם, המשתמשים, לעולם אינכם קוראים לפונקציית שחרור; אובייקטי הציור מתנקים כשמשתני ה־Perl המחזיקים בהם נעלמים. הכריכה אוכפת את הסדר ש־cairo דורשת, ומשחררת הקשר לפני המשטח שהוא מצייר אליו.

צעד 4: המתודות#

כל מתודת Perl היא פונקציה מובנית קטנה שקוראת את הידית, קוראת את הארגומנטים הסקלריים, ומבצעת קריאת C אחת. Cairo::Context::move_to קוראת את מצביע ההקשר ואת שתי הקואורדינטות וקוראת ל־cairo_move_to; Cairo::Context::set_source_rgba קוראת את המצביע ואת ארבעת רכיבי הצבע וקוראת ל־cairo_set_source_rgba; Cairo::Surface::write_to_png קוראת את המצביע ומחרוזת נתיב. המיפוי הוא מתודה אחת לקריאת C אחת:

Cairo::Context::move_to($cr, $x, $y)
    -> read context ptr from $cr; call cairo_move_to(ptr, x, y)

Cairo::Context::set_source_rgba($cr, $r, $g, $b, $a)
    -> call cairo_set_source_rgba(ptr, r, g, b, a)

Cairo::Surface::write_to_png($surface, $path)
    -> call cairo_surface_write_to_png(ptr, path)

The C-level signatures live in the binding and are settled there once. A user calling $cr->set_source_rgba(1, 0, 0, 0.5) never writes a signature and cannot get one wrong. That single point of truth for the C calls is the third of the three reasons a native binding beats scattered raw calls: object lifetime, ergonomics, and the signature written down once.

למה זה מגיע, ולמה לא#

עם ארבעת החלקים האלה (פתיחה פעם אחת, ידית כמספר שלם מבורך, DESTROY משחרר, מתודות מעל טבלת הפונקציות הפתורה) pperl מספק Cairo אמיתי ובטוח־זיכרון בלי הפצת CPAN מותקנת, בלי מהדר C, ובלי צעד בנייה. מודל הציור המלא של פרק הווקטור זמין, והאובייקטים מנהלים את עצמם.

Cairo’s core drawing API is scalars plus one opaque handle throughout, which is why Cairo was the first graphics library brought up this way: the four pieces above are the whole job. A library with a busier C interface needs more of the toolbox but not a different pattern. Structs are declared records, passed by value or by pointer; union-typed event records are declared unions the library fills in through a pointer; a library that calls back into your code gets a real function pointer from closure. What stays out of reach is the primer’s hard line: any prototype or declaration you would want derived from a header rather than written out by hand. The 2D game capstone works through a library on the busier end of that range.

המסקנה#

A graphics library whose C API is scalars plus opaque handles can be brought up on pperl as a native binding, and Cairo is the first one shipped: open the library once, hold each C object as a blessed integer, free it in DESTROY, and back each method with its C call settled in one place. The result is the upstream Cairo API, running natively. The next chapter stops describing and starts building: a drawing application on the native SDL2 binding, assembling the whole guide into something that runs.