How to get the function pointer of a static function? #8066
-
c# 9.0 function pointers question. step 1: class TestClass
{
public unsafe delegate* unmanaged<int> GetHandler()
{
return &CSharpFunc; // Error: CS8786.
}
static int CSharpFunc()
{
return default;
}
} step 2: class TestClass
{
public unsafe delegate* unmanaged<int> GetHandler()
{
return (delegate* unmanaged<int>)&CSharpFunc; // Error: CS8757.
}
static int CSharpFunc()
{
return default;
}
} step 3: class TestClass
{
public unsafe delegate* unmanaged<int> GetHandler()
{
return (delegate* unmanaged<int>)(delegate* managed<int>)&CSharpFunc; // Not Error.
}
static int CSharpFunc()
{
return default;
}
} Look at step 3, there is nothing wrong with doing this and the dll callbacks are fine. I'm not sure if it's composite logic to convert it that way. However, it runs without any abnormality for a short period of time, but when it runs for a longer period of time, will the GC clean up the garbage causing the dll to not be able to callback and have an abnormality? deepl translator. |
Beta Was this translation helpful? Give feedback.
Replies: 2 comments
-
Use using System.Runtime.InteropServices;
class TestClass
{
public unsafe delegate* unmanaged<int> GetHandler()
{
return (delegate* unmanaged<int>)&CSharpFunc;
}
[UnmanagedCallersOnly]
static int CSharpFunc()
{
return default;
}
} |
Beta Was this translation helpful? Give feedback.
-
The calling convention may differ. There are also different native calling conventions. You sample is just too trivial that doesn't differ with calling convention. There are also GC state transition between managed and unmanaged code. |
Beta Was this translation helpful? Give feedback.
Use
UnmanagedCallerOnly
to indicate your function will only be called from unmanaged code: