Skip to content

Latest commit

 

History

History
36 lines (25 loc) · 1.9 KB

File metadata and controls

36 lines (25 loc) · 1.9 KB

Interaction between Native and Managed Code for REAL

This short guide explains how REAL (float/Single) values are exchanged between managed C# code and native C++ using the eCLR. It follows the same patterns as other data types, with an important note on how floats are represented in the native interface.

C# Class

RealFB1.cs

  • Managed function block calls a [Native] method wrapper (RealFB1NativeMethods.Calculate(float, float)).
  • The wrapper defines the managed signature; the implementation is provided in native code.

Native Implementation

RealFB1NativeMethods-cli.cpp

  • Methods are exposed to managed code via the PInvoke prefix.
  • For REAL (Single), the generated native signature uses UInt32 for parameters and return value. This carries the IEEE-754 bit pattern of the float:
    • Reinterpret UInt32 → Single for computation.
    • Reinterpret Single → UInt32 for the return.
  • This preserves the exact bit pattern across the managed–native boundary.

C# Function Block

RealFB2.cs

  • A [Native] function block can implement its execution entirely in native code; only explicitly marked [Managed] members (e.g. __Init) run in C#.

Native Implementation

RealFB2-cli.cpp

  • PInvoke is used for the __Process method.
  • The native code accesses IN1, IN2, and OUT directly as Single fields of the function block instance.
  • An auto-generated ctor bridge is provided; this is standard boilerplate for native FB classes.

Notes and Best Practices

  • Use the provided UInt32-to-Single and Single-to-UInt32 reinterpretation pattern in native code to preserve float bit patterns exactly.
  • Avoid implicit integer conversions for REAL values; rely on bitwise reinterpretation as shown in the template.
  • The [Native] attribute and the PInvoke prefix define the managed–native boundary and enable seamless interop for REAL types.