Custom Marshalling Source Generation
The ability to use source generation for P/Invokes was introduced in .NET 7. This also included a mechanism for custom marshalling of types.
This sample implements and uses custom marshallers for a built-in type and a user-defined type, including both stateless and stateful marshallers. It demonstrates the usage of attributes relevant to source generation for interop:
Prerequisites
.NET 8 SDK Preview 7 or later
C++ compiler
- Windows:
cl.exe - Linux/macOS:
g++
- Windows:
Build and Run
In order to build and run, all prerequisites must be installed. The following are also required:
- On Linux/macOS, the C++ compiler (
g++) must be on the path. - The C++ compiler (
cl.exeorg++) anddotnetmust be the same bitness (32-bit versus 64-bit).- On Windows, the sample is set up to use the bitness of
dotnetto find the correspondingcl.exe
- On Windows, the sample is set up to use the bitness of
- On Linux/macOS, the C++ compiler (
Navigate to the root directory and run
dotnet buildRun the samples. Do one of the following:
- Use
dotnet run(which will build and run at the same time). - Use
dotnet buildto build the executable. The executable will be inbinunder a subdirectory for the configuration (Debugis the default).- Windows:
bin\Debug\custommarshalling.exe - Non-Windows:
bin/Debug/custommarshalling
- Windows:
- Use
Note: The way the sample is built is relatively complicated. The goal is that it's possible to build and run the sample with a simple dotnet run command with minimal requirements for pre-installed tools. Typically, real-world projects that have both managed and native components will use different build systems for each; for example, msbuild/dotnet for managed and CMake for native.
Visual Studio support
The src\custommarshalling.sln can be used to open the sample in Visual Studio 2022. In order to be able to build from Visual Studio, though, it has to be started from the correct developer environment. From the developer environment console, start it with devenv src\custommarshalling.sln. With that, the solution can be built. To run it, set the start project to custommarshalling.