Clarification on bool marshalling with LibraryImport #99440
-
Hello, I'm looking at the library design docs for
Essentially there should be a table that clarifies the behavior of bool marshalling for all combinations of {runtime marshalling enabled/disabled, P/Invoke with and without source generation, and where used: function argument, return value, member of struct, argument to managed delegate passed to function, etc}. |
Beta Was this translation helpful? Give feedback.
Replies: 4 comments 13 replies
-
The source generator reads
Delegates are not support with runtime marshalling disabled. You must use function pointers. There's a warning CA1420 for it.
This is not a matrix because many of these are not supported when runtime marshalling is disabled. Instead, the behavior should be clarified case by case. When runtime marshalling is disabled, |
Beta Was this translation helpful? Give feedback.
-
@huoyaoyuan Thanks very much for your reply. I find it super confusing that
Could you clarify what this means? The following code doesn't generate any warnings for me. Are you talking about something else? using System.Runtime.CompilerServices;
using System.Runtime.InteropServices;
[assembly: DisableRuntimeMarshalling]
namespace DelegateTest
{
[UnmanagedFunctionPointer(CallingConvention.Cdecl)]
public delegate void ManagedFunc();
public partial class NativeFuncs
{
[LibraryImport("lib.so")]
public static partial void func(ManagedFunc managedFunc);
}
public class DelegateTestClass
{
private void MyManagedFunc()
{
}
public void Func()
{
NativeFuncs.func(MyManagedFunc);
}
}
} |
Beta Was this translation helpful? Give feedback.
-
@huoyaoyuan I think you have answered my first question. Can I ask you to clarify the second question a bit more? Let's say I have the following managed delegate that returns [UnmanagedFunctionPointer(CallingConvention.Cdecl)]
public delegate bool ManagedFunc();
[LibraryImport("lib.so")]
public static partial void func(ManagedFunc managedFunc); I understand that |
Beta Was this translation helpful? Give feedback.
-
@jkoritzinsky Thanks for the explanation, that's helpful. I have a couple more questions just to make sure that I understand fully the design decisions.
You're talking about
As far as I understand, the marshalling rule for delegates with a bool argument or return type is 4-byte with runtime marshalling enabled and 1-byte with runtime marshalling disabled. Is that correct? If so then any reason why you decided not to require the user to specify the marshalling rule like for LibraryImport? There may be some users who stick with |
Beta Was this translation helpful? Give feedback.
MarshalAs
has no effect on raw DllImport.The source generator reads
MarshalAs
on LibraryImport declaration, and translate it into appropriate form in generated DllImport.