CtrlK
BlogDocsLog inGet started
Tessl Logo

tessl/npm-tns-platform-declarations

Platform-specific TypeScript declarations for NativeScript for accessing native objects

84

1.23x
Overview
Eval results
Files

native-interop.mddocs/

Native Interoperability

Advanced native code integration layer providing pointer arithmetic, memory management, type conversion, and native function calls specifically for iOS platform development. Essential for low-level native iOS API access.

Capabilities

Pointer Management

Core pointer operations for direct memory access and native API integration.

declare module interop {
  /**
   * A type that represents a void* pointer for direct memory access
   */
  interface Pointer {
    /**
     * Create a new pointer with the given offset
     * @param offset - The offset in bytes
     */
    new(offset: number);

    /**
     * Create a new pointer by adding an offset to the current pointer
     * @param offset - The offset in bytes  
     * @returns New pointer with added offset
     */
    add(offset: number): Pointer;

    /**
     * Create a new pointer by removing an offset from the current pointer
     * @param offset - The offset in bytes
     * @returns New pointer with subtracted offset
     */
    subtract(offset: number): Pointer;

    /**
     * Convert the value of this instance to a number
     * @returns Numeric representation of the pointer address
     */
    toNumber(): number;
  }

  var Pointer;

  /**
   * A pointer that will free the memory it points to automatically when garbage collected
   */
  interface AdoptedPointer extends Pointer {
  }
}

Usage Examples:

// Create and manipulate pointers
const ptr = new interop.Pointer(0x1000);
const offsetPtr = ptr.add(64); // Add 64 bytes
const backPtr = offsetPtr.subtract(32); // Subtract 32 bytes

// Convert pointer to numeric address
const address = ptr.toNumber();
console.log(`Pointer address: 0x${address.toString(16)}`);

Memory Allocation

Memory management functions for allocating and releasing native memory.

declare module interop {
  /**
   * Make the pointer adopted - it will hold its memory automatically
   * @param ptr - The pointer to adopt
   * @returns AdoptedPointer that will auto-free memory
   */
  function adopt(ptr: Pointer): AdoptedPointer;

  /**
   * Allocate memory block
   * @param size - The size in bytes to allocate
   * @returns AdoptedPointer to allocated memory
   */
  function alloc(size: number): AdoptedPointer;

  /**
   * Release the memory of a pointer (should not be adopted)
   * @param ptr - Pointer to the memory to free
   */
  function free(ptr: Pointer): void;

  /**
   * Return the size of the provided type
   * @param type - Class constructor, instance, struct, reference, protocol, or function
   * @returns Size in bytes of the type
   */
  function sizeof(type: any): number;

  /**
   * Get a pointer to the backing native object from a JavaScript object
   * @param instance - Class constructor, instance, struct, reference, protocol, function, or block
   * @returns Pointer to the native object
   */
  function handleof(instance: any): Pointer;

  /**
   * Wrap an NSData instance in an ArrayBuffer
   * @param data - NSData instance to wrap
   * @returns ArrayBuffer wrapping the data
   */
  function bufferFromData(data: NSData): ArrayBuffer;
}

Usage Examples:

// Allocate and manage memory
const buffer = interop.alloc(1024); // Allocate 1KB, auto-freed
const rawPtr = new interop.Pointer(0x2000);
const adoptedPtr = interop.adopt(rawPtr); // Now auto-freed

// Get size information
const nsStringSize = interop.sizeof(NSString);
const intSize = interop.sizeof(interop.types.int32);

// Get native handle
const nsString = NSString.stringWithString("Hello");
const handle = interop.handleof(nsString);

// Convert NSData to ArrayBuffer
const nsData = NSData.dataWithContentsOfFile("/path/to/file");
const buffer = interop.bufferFromData(nsData);

Reference Types

Typed references for passing values by reference to native functions.

declare module interop {
  /**
   * A type that wraps a pointer and allows read/write operations on its value
   */
  interface Reference<T> {
    /** The referenced value */
    value: T;
  }

  /**
   * Reference constructor for creating typed references
   */
  var Reference: {
    /**
     * Create a new reference around a value
     * @param value - JavaScript value to initialize the reference
     * @returns Reference wrapping the value
     */
    new <T>(value?: T): Reference<T>;

    /**
     * Create a reference from pointer with given type
     * @param type - The type to interpret the pointer as
     * @param data - Pointer to the data  
     * @returns Typed reference to the pointer data
     */
    new <T>(type: Type<T>, data: Pointer): Reference<T>;

    /**
     * Create a new reference around a value with explicit type
     * @param type - The type to interpret the value as
     * @param value - Value to reference
     * @returns Typed reference to the value
     */
    new <T>(type: Type<T>, value: any): Reference<T>;

    /**
     * Access values using pointer arithmetic
     */
    [index: number]: any;
  }
}

Usage Examples:

// Create references for passing by reference
const intRef = new interop.Reference<number>(42);
const stringRef = new interop.Reference<string>("Hello");

// Use with native functions that expect references
someNativeFunction(intRef);
console.log(intRef.value); // May be modified by native function

// Create typed references from pointers
const ptr = interop.alloc(interop.sizeof(interop.types.int32));
const typedRef = new interop.Reference(interop.types.int32, ptr);
typedRef.value = 100;

// Array-style access for pointer arithmetic
typedRef[0] = 100; // Same as typedRef.value = 100
typedRef[1] = 200; // Next int32 in memory

Function References

Native function pointer support for callback scenarios, including Objective-C blocks.

declare module interop {
  interface FunctionReference<T> {
    (...params);
  }

  /**
   * Create a function reference that can be marshalled as a native function pointer
   * The JavaScript reference must be held alive as long as the native code needs it
   */
  var FunctionReference: {
    new <T>(func: T): FunctionReference<T>;
  }

  /**
   * Objective-C Block type for callback scenarios
   * Blocks are Objective-C's closure implementation
   */
  interface Block<T> {
    (...params);
  }

  /**
   * Create an Objective-C block from a JavaScript function
   * The JavaScript reference must be held alive as long as the native code needs it
   */
  var Block: {
    new <T>(func: T): Block<T>;
  }
}

Usage Examples:

// Create function reference for native callbacks
const callback = (result: number) => {
  console.log(`Native callback result: ${result}`);
};

const funcRef = new interop.FunctionReference(callback);

// Pass to native function expecting callback
someNativeFunctionWithCallback(funcRef);
// Keep funcRef alive as long as native code might call it

// Create Objective-C block for iOS callbacks
const blockCallback = (success: boolean, error: NSError) => {
  if (success) {
    console.log("Operation completed successfully");
  } else {
    console.log(`Operation failed: ${error.localizedDescription}`);
  }
};

const block = new interop.Block(blockCallback);

// Pass block to Objective-C method expecting a completion handler
someNSObjectMethod.performOperationWithCompletion(block);
// Keep block reference alive during async operation

Type System

Comprehensive type definitions for native type conversion and marshalling.

declare module interop {
  interface Type<T> {
    (ptr: Pointer): T;
  }

  var types: {
    /** Void type */
    "void": Type<void>;
    /** Boolean type */
    bool: Type<boolean>;
    /** 8-bit signed integer */
    int8: Type<number>;
    /** 8-bit unsigned integer */
    uint8: Type<number>;
    /** 16-bit signed integer */
    int16: Type<number>;
    /** 16-bit unsigned integer */
    uint16: Type<number>;
    /** 32-bit signed integer */
    int32: Type<number>;
    /** 32-bit unsigned integer */
    uint32: Type<number>;
    /** 64-bit signed integer */
    int64: Type<number>;
    /** 64-bit unsigned integer */
    uint64: Type<number>;
    /** 32-bit floating point */
    float: Type<number>;
    /** 64-bit floating point */
    double: Type<number>;

    /** UTF-8 C string type */
    UTF8CString: Type<Reference<number>>;
    /** Unicode character type */
    unichar: Type<string>;

    /** Objective-C id type */
    id: Type<any>;
    /** Objective-C protocol type */
    protocol: Type<any>;
    /** Objective-C class type */
    "class": Type<any>;
    /** Objective-C selector type */
    selector: Type<string>;
  }
}

Usage Examples:

// Use primitive types
const intSize = interop.sizeof(interop.types.int32);
const doubleSize = interop.sizeof(interop.types.double);

// Create typed references
const intRef = new interop.Reference(interop.types.int32, 42);
const floatRef = new interop.Reference(interop.types.float, 3.14);

// Work with C strings
const cStringRef = new interop.Reference(interop.types.UTF8CString);

Struct Types

Support for C struct definitions and manipulation.

declare module interop {
  /**
   * A type for JavaScript constructors for C structs
   */
  interface StructType<T> extends Type<T> {
    /**
     * Create a new instance of the struct
     */
    new(): T;

    /**
     * Create a new instance and initialize from provided object fields
     * @param obj - Initializer object
     * @returns New struct instance
     */
    new(obj: T): T;

    /**
     * Create a new struct by copying memory from pointer
     * @param obj - Pointer to struct data
     * @returns New struct instance
     */
    new(obj: Pointer): T;

    /**
     * Check two structs for equality
     * @param left - First struct to compare
     * @param right - Second struct to compare  
     * @returns True if structs are equal
     */
    equals(left: T, right: T): boolean;
  }
}

Usage Examples:

// Define a struct type (example - actual structs depend on iOS SDK)
interface CGPoint {
  x: number;
  y: number;
}

// Assuming CGPoint is available as StructType
const point1 = new CGPoint();
point1.x = 10;
point1.y = 20;

const point2 = new CGPoint({ x: 30, y: 40 });

// Compare structs
const areEqual = CGPoint.equals(point1, point2);

Unmanaged References

Support for unmanaged object references and memory ownership transfer.

declare module interop {
  /**
   * A type for propagating an unmanaged object reference
   * When you use this type, you become partially responsible for keeping the object alive
   */
  interface Unmanaged<T> {
    /**
     * Get the value as a managed reference and consume an unbalanced retain
     * Use when a function returns unmanaged reference and you're responsible for releasing
     * @returns Managed reference to the object
     */
    takeRetainedValue(): T;

    /**
     * Get the value as a managed reference without consuming an unbalanced retain  
     * Use when a function returns unmanaged reference and you're not responsible for releasing
     * @returns Managed reference to the object
     */
    takeUnretainedValue(): T;
  }
}

Usage Examples:

// Handle unmanaged references (typically from native functions)
declare function getNativeObjectUnmanaged(): interop.Unmanaged<NSString>;

// Take ownership of returned object
const managedString = getNativeObjectUnmanaged().takeRetainedValue();
// You are now responsible for this object

// Or get without taking ownership
const borrowedString = getNativeObjectUnmanaged().takeUnretainedValue();  
// Someone else manages this object

Error Handling

Native error handling integration with NSError.

declare module interop {
  interface NSErrorWrapper extends Error {
    /** The wrapped NSError instance */
    error: NSError;
  }

  var NSErrorWrapper: {
    new(error: NSError): NSErrorWrapper;
    (error: NSError): NSErrorWrapper;
    prototype: NSErrorWrapper;
  }
}

Usage Examples:

// Handle NSError in JavaScript
try {
  // Some operation that might produce NSError
  const result = someNativeOperationThatMightFail();
} catch (error) {
  if (error instanceof interop.NSErrorWrapper) {
    const nsError = error.error;
    console.log(`Native error: ${nsError.localizedDescription}`);
    console.log(`Error code: ${nsError.code}`);
  }
}

// Create NSErrorWrapper from NSError
const nsError = NSError.errorWithDomainCodeUserInfo("MyDomain", 100, null);
const wrapper = new interop.NSErrorWrapper(nsError);

Advanced Usage Patterns

Memory Management Best Practices

// Use adopted pointers for automatic cleanup
const buffer = interop.alloc(1024); // Automatically freed

// Manual management when needed
const rawPtr = new interop.Pointer(0x1000);
try {
  // Use rawPtr...
} finally {
  interop.free(rawPtr);
}

// Reference management  
const objRef = new interop.Reference<NSString>();
someNativeFunctionThatSetsRef(objRef);
// objRef.value now contains the result

Type Conversion Patterns

// Converting between JavaScript and native types
const jsNumber = 42;
const nativeInt = new interop.Reference(interop.types.int32, jsNumber);

// Working with C strings
const jsString = "Hello World";
const cString = NSString.stringWithString(jsString).UTF8String;

// Buffer operations
const nsData = NSData.dataWithContentsOfFile("/path/to/file");
const buffer = interop.bufferFromData(nsData);
const uint8Array = new Uint8Array(buffer);

Install with Tessl CLI

npx tessl i tessl/npm-tns-platform-declarations

docs

android-platform.md

index.md

ios-platform.md

native-interop.md

nativescript-widgets.md

tile.json