AtlatestRepositorysigil-ffi

sigil-ffi / tree / testffi-test-lib.c

1/* Tiny shared library for FFI dlopen smoke tests.
2 *
3 * Compiled during test with:
4 * cc -shared -fPIC -o libffi-test.so ffi-test-lib.c
5 */
6
7#include <string.h>
8#include <stdlib.h>
9
10/* Basic arithmetic — tests int and double marshaling */
11int add_ints(int a, int b)
13 return a + b;
16double multiply_doubles(double a, double b)
18 return a * b;
21/* Mixed types — tests cross-type signatures */
22double int_to_double(int x)
24 return (double)x * 2.5;
27int double_to_int(double x)
29 return (int)x;
32/* String handling — tests string marshaling across dlopen */
33int string_length(const char *s)
35 return (int)strlen(s);
38/* Returns a static string — tests string return */
39const char *greeting(void)
41 return "hello from ffi-test-lib";
44/* Pointer operations — tests pointer passing */
45void fill_buffer(int *buf, int count, int value)
47 for (int i = 0; i < count; i++) {
48 buf[i] = value + i;
49 }
52int sum_buffer(const int *buf, int count)
54 int total = 0;
55 for (int i = 0; i < count; i++) {
56 total += buf[i];
57 }
58 return total;
61/* Struct-by-value — tests dyncall struct passing */
62typedef struct {
63 double x;
64 double y;
65} Point;
67Point make_point(double x, double y)
69 Point p = { x, y };
70 return p;
73double point_distance(Point a, Point b)
75 double dx = b.x - a.x;
76 double dy = b.y - a.y;
77 return dx * dx + dy * dy; /* squared distance, avoids needing sqrt */
80/* Callback test — calls a function pointer */
81typedef int (*IntBinaryFn)(int, int);
83int apply_fn(IntBinaryFn fn, int a, int b)
85 return fn(a, b);