Native C library binding
Build this C fixture as a shared library for the architecture of the Atom executable. Save as native_fixture.c. On Linux use cc -std=c17 -fPIC -shared native_fixture.c -o native_fixture.so. On macOS use cc -std=c17 -dynamiclib native_fixture.c -o native_fixture.dylib. On MinGW use gcc -std=c17 -shared native_fixture.c -o native_fixture.dll.
Export one C function
Start with twice. Its fixed-width signed parameter and return type map directly to i32 in Atom.
EXPORT int32_t twice(int32_t value)
{
return value * 2;
}
Show full source 46 lines
#include <stdarg.h>
#include <stdint.h>
#ifdef _WIN32
#define EXPORT __declspec(dllexport)
#else
#define EXPORT __attribute__((visibility("default")))
#endif
typedef struct { float x, y; } Vec2;
typedef int32_t (*Transform)(int32_t);
EXPORT int32_t twice(int32_t value)
{
return value * 2;
}
EXPORT Vec2 make_vec(float x, float y)
{
return (Vec2){x, y};
}
EXPORT float dot(Vec2 a, Vec2 b)
{
return a.x * b.x + a.y * b.y;
}
EXPORT void sample_sum(const float *samples, uint32_t count, float *out)
{
*out = 0.0f;
for (uint32_t i = 0; i < count; ++i) *out += samples[i];
}
EXPORT int32_t apply(Transform transform, int32_t value)
{
return transform(value);
}
EXPORT double gain(double value, ...)
{
va_list trail;
va_start(trail, value);
double factor = va_arg(trail, double);
va_end(trail);
return value * factor;
}
Save as native.atom and run atom run native.atom -- ./native_fixture.so or pass the platform equivalent. The example covers scalar calls, C records in both directions, arrays and output parameters by pointer, a synchronous callback and an explicitly promoted variadic argument.
Declare the same signature in Atom
The list describes the arguments in order. The last i32 describes the return value. The complete script calls twice(12) and checks for 24.
twice = ffi.bind(library, 'twice', [i32], i32)
Show full source 36 lines
use binary
use ffi
use os
func increment(value):
return value + 1
library = ffi.load(os.args[0])
try:
vec2 = binary.layout({x = f32, y = f32})
twice = ffi.bind(library, 'twice', [i32], i32)
make_vec = ffi.bind(library, 'make_vec', [f32, f32], vec2)
dot = ffi.bind(library, 'dot', [vec2, vec2], f32)
sample_sum = ffi.bind(library, 'sample_sum', [ptr, u32, ptr], void)
apply = ffi.bind(library, 'apply', [ptr, i32], i32)
gain = ffi.bind(library, 'gain', [f64, f64], f64, 1)
point = make_vec(3, 4)
assert(twice(12) == 24 and dot(point, point) == 25)
samples = create(f32, 3)
samples[0] = 1.5
samples[1] = 2.5
samples[2] = 3.0
result = create(f32, 1)
sample_sum(samples, count(samples), result)
assert(result[0] == 7.0 and gain(2, 1.5) == 3.0)
callback = ffi.callback(increment, [i32], i32)
try:
assert(apply(callback, 41) == 42)
finally:
ffi.free(callback)
print('Native calls passed.')
finally:
ffi.close(library)