dotnet / dotnet/docs

Interop Guidance should contain enum types

Open
#25,469 0 comments 0 reactions 0 assignees View on GitHub
dotnet-fundamentals/svc
Dominant language
No language data
Stars
4.8k
Forks
6.1k
Avg merge
19h 10m
Merged PRs (30d)
268

Description

Current interop guidance does not include any information about enums.

But enums with same underlying type seems to be blittable. For example the following works in C# , and it should not be a problem when corresponding structure in C or C++ has also the same types and layout.:

```csharp

enum Foo : int { A, B, C }
enum Bar : short { A, B, C }

[StructLayout(LayoutKind.Sequential)]
struct Baz
{
public Foo Foo;
public Bar Bar;
}

class Program
{
static void Main(string[] args)
{
var x = new Baz { Foo = Foo.B, Bar = Bar.C };
Blit(x, out var y);
Console.WriteLine($"{y.Foo}/{y.Bar}");
}

private unsafe static void Blit(in TValue x, out TValue y)
where TValue : unmanaged
{
fixed (byte* inval = (byte*)&x)
fixed (byte* outval = (byte*)&y)
{
int size = Unsafe.SizeOf();
for (int i = 0; i < size; ++i)
{
outval[i] = inval[i];
}
}
}
}

```

---
#### Document Details

⚠ *Do not edit this section. It is required for docs.microsoft.com ➟ GitHub issue linking.*

* ID: 6ea501d3-d963-c5dc-342d-ee82c92d1850
* Version Independent ID: e58f3d16-8083-0efe-0057-e21dbebb262f
* Content: [Native interoperability best practices - .NET](https://docs.microsoft.com/en-us/dotnet/standard/native-interop/best-practices)
* Content Source: [docs/standard/native-interop/best-practices.md](https://github.com/dotnet/docs/blob/main/docs/standard/native-interop/best-practices.md)
* Product: **dotnet-fundamentals**
* GitHub Login: @jkoritzinsky
* Microsoft Alias: **jekoritz**

Contributor guide

Open the contributing guide

Assessment

This issue has not been assessed yet.

Get new issues in your inbox

A short digest of beginner-friendly GitHub issues.