Sharing the custom marshalled type across libraries
I followed the guide thoroughly https://learn.microsoft.com/en-us/dotnet/standard/native-interop/tutorial-custom-marshaller and source code is in here https://github.com/dotnet/samples/blob/main/core/interop/source-generation/custom-marshalling/src/custommarshalling/NativeLib.cs
so far it works, but things goes south when i try to use the
ErrorData
outside of host library
code used to test it out:
PS: unlike the original source code, i've made modification to ErrorData and their marshallers by making everything public just for testing.
it generates SYSLIB1051 error error SYSLIB1051: Runtime marshalling must be disabled in this project by applying the 'System.Runtime.CompilerServices.DisableRuntimeMarshallingAttribute' to the assembly to enable marshalling this type. The generated source will not handle marshalling of parameter 'errorData'. (https://learn.microsoft.com/dotnet/fundamentals/syslib-diagnostics/syslib1051)
Use custom marshallers in source-generated P/Invokes - .NET
Learn how to use the CustomMarshallerAttribute and implement a custom marshaller for use with source generation.
GitHub
samples/core/interop/source-generation/custom-marshalling/src/custo...
Sample code referenced by the .NET documentation. Contribute to dotnet/samples development by creating an account on GitHub.
3 Replies
TLDR:
The error still persists if i removed the
NativeMarshalling
attribute and manually added MarshalUsing
to each argument/return
I guess the solution was to disable runtime marshalling with [assembly: System.Runtime.CompilerServices.DisableRuntimeMarshalling]
The issue with such solution for me was that it triggers CA1420: Property, type, or attribute requires runtime marshalling
for delegates marked with [UnmanagedFunctionPointer(CallingConvention.Cdecl)]
or any use of Marshal.GetFunctionPointerForDelegate
with delegates managed types (even if they have NativeMarshaller
)I believe you want UnmanagedCallersOnly nowadays. https://learn.microsoft.com/en-us/dotnet/csharp/language-reference/proposals/csharp-9.0/function-pointers
Function pointers - C# feature specifications
This feature specification describes function pointers, which are unmanaged delegates. They are typically used to avoid the allocations necessary to instantiate a delegate object.
that would restrict me from using the managed types aswell as making the function static, right?
thank you for the suggestion, i'll do that