C FFI Bindings for rustp2p
This directory contains C FFI bindings for the rustp2p library, enabling the use of rustp2p from C, C++, and other languages that can call C functions (including JavaScript/TypeScript via FFI mechanisms like Bun FFI, Node-FFI, etc.).
Building
To build the FFI library:
This will generate:
- A shared library:
target/release/librustp2p_c_ffi.so(Linux),librustp2p_c_ffi.dylib(macOS), orrustp2p_c_ffi.dll(Windows) - A static library:
target/release/librustp2p_c_ffi.a(Unix) orrustp2p_c_ffi.lib(Windows)
C Header File
The C header file rustp2p.h is included in this directory and provides the API declarations.
API Overview
Builder API
-
Create a new builder:
Rustp2pBuilder* builder = ; -
Configure the builder:
; ; ; ; ; ; -
Build the endpoint:
Rustp2pEndpoint* endpoint = ;
Endpoint Operations
-
Send data:
const char* message = "Hello, peer!"; ; -
Receive data:
Rustp2pRecvData* recv_data = ; if -
Cleanup:
;
Example
See examples/simple_example.c for a complete working example.
To build and run the example:
# Build the FFI library
# Compile the C example
# Run the example
LD_LIBRARY_PATH=../../target/release
Using with JavaScript/TypeScript
The FFI bindings can be used with JavaScript/TypeScript through various FFI mechanisms:
Bun FFI
import { dlopen, FFIType, suffix } from "bun:ffi";
const lib = dlopen(`librustp2p_c_ffi.${suffix}`, {
rustp2p_builder_new: {
returns: FFIType.ptr,
args: [],
},
rustp2p_builder_node_id: {
returns: FFIType.i32,
args: [FFIType.ptr, FFIType.cstring],
},
// ... other functions
});
// Use the library
const builder = lib.symbols.rustp2p_builder_new();
lib.symbols.rustp2p_builder_node_id(builder, "10.0.0.1");
// ...
Node.js FFI
const ffi = require;
const ref = require;
const lib = ffi.;
const builder = lib.;
lib.;
// ...
Error Codes
RUSTP2P_OK(0): SuccessRUSTP2P_ERROR(-1): Generic errorRUSTP2P_ERROR_NULL_PTR(-2): NULL pointer providedRUSTP2P_ERROR_INVALID_STR(-3): Invalid stringRUSTP2P_ERROR_INVALID_IP(-4): Invalid IP addressRUSTP2P_ERROR_BUILD_FAILED(-5): Builder build failedRUSTP2P_ERROR_WOULD_BLOCK(-6): Operation would blockRUSTP2P_ERROR_EOF(-7): End of file/stream
Thread Safety
The FFI bindings use Tokio runtime internally. Each endpoint has its own runtime instance. The functions are designed to be safe to call from multiple threads, but it's recommended to use one endpoint per thread or use proper synchronization.
License
Apache-2.0 (same as rustp2p)