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 and has the
staticattribute, and its containing type also has the[BurstCompile]attribute.[BurstCompile] - 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 or
public.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 attribute, or compile and cache a with . Instead, you call the method in the same way as any other static C# method.
[MonoPInvokeCallback]FunctionPointer<T>BurstCompiler.CompileFunctionPointer<T>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, is printed to the log.
float4(98f, 2f, -3f, 4f)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 to the BurstCompile options. This prevents the Post Processor from running on the code:
DisableDirectCall = true[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; }}