文档

Unity Engine

Download Unity

Unity Engine

Calling Burst-compiled code

Call Burst compiled code from managed code.
阅读时间2 分钟最后更新于 12 小时前

You can call Burst-compiled methods directly from managed code. To call a Burst-compiled method directly, it must meet the following requirements:
  • The method is
    static
    and has the
    [BurstCompile]
    attribute, and its containing type also has the
    [BurstCompile]
    attribute.
  • The method isn't generic, and its containing type isn't generic.
  • The containing type, the method, and all the types in the method's signature are
    public
    or
    internal
    .
  • The argument and return types follow the same restrictions as function pointers. For example, pass structs by reference.
Unlike function pointers, you don't need to declare a delegate type, add the
[MonoPInvokeCallback]
attribute, or compile and cache a
FunctionPointer<T>
with
BurstCompiler.CompileFunctionPointer<T>
. Instead, you call the method in the same way as any other static C# method.
The following example shows a Burst-compiled utility class. Because it uses structs, it passes by reference per the function pointer rules.
[BurstCompile]public static class MyBurstUtilityClass{ [BurstCompile] public static void BurstCompiled_MultiplyAdd(in float4 mula, in float4 mulb, in float4 add, out float4 result) { result = mula * mulb + add; }}
Use this method from managed code like so:
public class MyMonoBehaviour : MonoBehaviour{ void Start() { var mula = new float4(1, 2, 3, 4); var mulb = new float4(-1,1,-1,1); var add = new float4(99,0,0,0); MyBurstUtilityClass.BurstCompiled_MultiplyAdd(mula, mulb, add, out var result); Debug.Log(result); }}
If you attach this script to an object and run it,
float4(98f, 2f, -3f, 4f)
is printed to the log.

Code transformation

Burst uses source generation to intercept the call-site and redirect it to a call to a cached function pointer. For more information, refer to the documentation on Function pointers.
To disable the direct call transformation, add
DisableDirectCall = true
to the BurstCompile options. This prevents the Post Processor from running on the code:
[BurstCompile]public static class MyBurstUtilityClass{ [BurstCompile(DisableDirectCall = true)] public static void BurstCompiled_MultiplyAdd(in float4 mula, in float4 mulb, in float4 add, out float4 result) { result = mula * mulb + add; }}

Additional resources