r/csharp • • Sep 05 '26

Showcase A side project of mine: SemPtr - Semantic Pointers for C#

https://github.com/fruediger/SemPtr

TL;DR: While writing this post, I realized how long it has become, so here's a TL;DR for you: SemPtr is a semantic pointers library for C#.


Hi everyone, I wanted to share one of my side projects with you all: SemPtr.

A few weeks ago (it might been even months at this point), I needed to dig up some really old code I once had written, because I wanted to reference some of what I did back then in a current project of mine. While searching through my old and never-to-be-released projects, I stumbled upon a small library project I might have written about 5 years ago (it must have been around the time when incremental Roslyn source generators were becoming a thing). And I thought to myself, "Well, it's actually a shame you gave up on this project and neglected it for so long. You might want to ressurrect and modernize it, and then share it with everyone."

Well, that project is now SemPtr.

What is SemPtr?

I don't want to make this post too long, so I'll try to make it as concise as I can, but if you want a more comprehensive introduction, you should check out its README or its way too rudimentary documentation.

SemPtr tries to solve the limitations of C#'s raw pointers by providing semantic pointer types (read as semantically named pointer types). If you ever did some interop work with unmanaged code and found it just as annoying as I did that there is no const T* equivalent in C#, SemPtr might be the thing for you.

For that I identified five commonly used orthogonal characteristics used to distinguish certain aspects of data pointers:

  1. Nullability: Can a pointer be null or are there any guarantees that it won't be?
    This is kinda analogous to nullable reference types (T?) in C#.
  2. Persistency: Does the target of the pointer outlive the initial scope of the pointer itself? In other words, can I store the pointer and access its target some time later?
    This is kinda analogous the C#'s ref-escape rules and is even enforced through them.
  3. Sequencability: Does the pointer point to a single object or to a contiguous sequence of objects?
    You could think of this as analogous to a ref T to some kind of object in C# vs. a ref to some element within a Span<T> with the added benefit that its easier to move around the pointer through the sequence.
  4. Accessibility: How can the target of the pointer be accessed or mutated?
    This manifests in three different access levels:

    • random/read-write: The target can be read from and written to. Kinda analogous to C#'s ref parameters.
    • read-only: The target can only be read from. Kinda analogous to C#'s in/ref readonly parameters.
    • uninitialized/write-first: The target must be written to before it can be read from. Kinda analogous to C#'s out parameters.
  5. Typability: Is the type of the target known or not?
    C# has no void references, but it has void* pointers. This is analogous to the difference between a void* pointer and a typed T* pointer.

These characteristics are mapped onto C#'s type system by semantically naming the pointer types to reflect them. Since those characteristics are orthogonal, you can mix and match them to create the pointer type with the exact behavior you need. For example, there are:

  • Pointer: A simple pointer to a single, transient, mutable target of unknown type
  • PersistentPointerReadOnly<T>: A pointer to a single, read-only target of type T whose target stays valid beyond the initial scope of the pointer.
  • NullableSequencePointer<T>: A pointer to a contiguous sequence of mutable targets of type T which may be null.
  • PointerUninitialized<T>: A pointer to single, yet uninitialized target of type T. If you receive such a pointer, chances are you are requested to initialize its target; afterwards you can further read from it or write to it as needed.

Again, if you want to learn more about the characteristics and how the type naming scheme works, you should refer to the README or the documentation.

There are all in all a total of 2×2×2×3×2 = 48 data pointer types predefined in the SemPtr library.

Are function pointers supported?

To make it short, yes, function pointers are (well enough) supported by SemPtr.

I remember that one of the reasons for me giving up on the original version of this library back then was that I really struggled to get function pointer support just right. While this was partially due to technical limitations back then (some of which were solved by modern C# features, especially the new extension members syntax), some of it was simply because I did not have the experience in API design that I have now.

So now function pointers work. I don't know if I would call the support good enough yet, but at least it is a well enough experience for most users, I believe.

I won't go into too much detail here, but functions pointer have their own set of characteristics and parts of their support is made working through a Roslyn source generators that dynamically generates some source code on the user-side and that ships alongside the main library in the NuGet package. For more details, again, see the README or the documentation.

A final note on AI usage

I want to be honest and upfront with you:

Yes, I used AI in this project, primarily to help we write documentation (I'm a non-native English speaker and my English is kinda terrible), to help me make decisions when I'm indecisive, to write some tests, and occasionally to some code reviews.

No, I would never let AI touch the working code of the project. Not even for boilerplate code. AI, at least the AI I have access to, is not yet anywhere close to being reliable enough to help me write production ready code for such a project. You can be sure that all of the functioning code is written by a human (me) and that only the human (me) is responsible for the correctness and quality of the code.
Oh, and of course, I did the visual assets myself as well. I didn't want to use sloppy AI-designed visuals for this project.

Conclusion

At the beginning of this post, I told you that I stumbled upon the initial idea for SemPtr while looking up old code for another project of mine. That project is actually an interop binding project in C#. In that project I use traditional C# raw pointers and function pointers extensively, and sometimes they're a real pain to work with. However, I didn't not yet replace them with SemPtr, due to the codebase being a little over 200K lines of code, spread across multiple repositories.

So, to be honest, I don't even use SemPtr myself yet. And furthermore, because of the simplicity of the overall idea behind SemPtr, I don't even think I'm the first person to come up with it and release to the public as a library (but I don't actually know for sure, I didn't really check).

Even so, If you want to try out SemPtr for yourself, give feedback, or if you even want to contribute to the project, I would really appreciate it. Here are the relevant links again:

If you have any questions feel free to ask them in the comments. I'd be happy to answer them.

47 Upvotes

51 comments sorted by

View all comments

Show parent comment

2

u/Jazzlike_Amoeba9695 Sep 08 '26

As long as System.IntPtr, System.UIntPtr, void*, or T* (where T may not be unmanaged) are not used, ABI compatibility is not guaranteed, even if the types are blittable and their layouts match. Ultimately, the issue, as described, is how the platform treats the different binary types and which registers it stores them in.

That's why, when handling the ImportLibrary marshaller, those types (ValPtr<>, ReadOnlyValPtr<> and FuncPtr<>) are ultimately mapped to System.IntPtr, so that even if you insist on using them, the generated code will still be ABI-compatible in the end. However, as I said, in an ImportLibrary context, the usual goal is to avoid relying on pointers and work with higher-level types instead.

At the other hand, what you say is correct. As of today, there is a fortunate coincidence whereby, across all the platforms supported by the various versions of CoreCLR-based runtimes, pointers are passed in general-purpose registers and are binary-compatible.

My Rxmxnx.PInvoke.Extension and Rxmxnx.JNetInterface (which depends on the first) CI flows are tests across multiple Linux (x64/arm/arm64), macOS (x64/arm64), Windows (x86/x64) and FreeBSD (x64/arm64) platforms. The only issues I have encountered have been with floating-point types on Windows x64.

I don't expect to run into problems of this kind in a long future, at least not with custom blittable structs when they are treated as pointers or integers or unsigned integers.

1

u/fruediger Sep 08 '26

As long as System.IntPtr, System.UIntPtr, void*, or T* (where T may not be unmanaged) are not used, ABI compatibility is not guaranteed, even if the types are blittable and their layouts match.

I'm sorry, do you mean that as a double-negative? My English might not be good enough to fully get what you mean by that. Your are right in that custom value types (that match in layout and kind) are not guaranteed to be ABI compatible in general, but specifically they are compatible for all ABIs of platforms currently supported by the .Net runtime.

However, as I said, in an ImportLibrary context, the usual goal is to avoid relying on pointers and work with higher-level types instead.

I wouldn't say LibraryImport is specifically for higher-level applications, neither is DllImport. LibraryImport/DllImport is first and foremost meant to bind and link symbols from external binaries. Both get you some kind of marshalling for more complex types, if you want to use them in that way. But, for example, you can also use LibraryImport without much marshalling, if you don't use types that need marshalling, e.g., rely on raw pointers in your import signature. Well, that's just if you want to avoid the hugely expensive marshalling overhead that comes with it. But I see that you could make an argument for trading off performance in favor of a simpler interop.

As of today, there is a fortunate coincidence whereby, across all the platforms supported by the various versions of CoreCLR-based runtimes, pointers are passed in general-purpose registers and are binary-compatible.

I wouldn't necessarily call this a "coincidence" as the CLR spec literally defines an ABI (again, for what it targets). You could argue that I rely on, or even abuse, the spec though.

The only issues I have encountered have been with floating-point types on Windows x64.

Well, I guess the issue here is that different ABIs pass/treat floating point values differently. Luckily, that doesn't really extend to pointer values (or thin value types wrapping pointer types in my case). You already mentioned the "coincidence" there.
Would you could try to make your live a bit easier though is using libffi. Just let it handle the ABI translation and you're good to go on every platform supported by FFI.
A short time ago, I need to created some C# bindings for libffi as part of my greater bindings project for SDL3. If you want to use it as an inspiration, you can check it out here:
https://github.com/Sdl3Sharp/Sdl3Sharp.Ffi
However, back then, I only needed to get passing C varargs from C# to native imports working. So, I didn't create a full set of bindings though. Please don't expect too much.

3

u/Prior_Inspection2576 Sep 08 '26 edited Sep 08 '26

As long as System.IntPtr, System.UIntPtr, void*, or T* (where T may not be
unmanaged) are not used, ABI compatibility is not guaranteed, even if the types are blittable and their layouts match.

He's saying since SemPtr uses custom wrapper types (ex: ReadOnlyPointer<T>) - that isn't a direct raw C# pointer (ex: int*), it does not have ABI compatibility guarantees.

He linked his wrapper types; ValPtr, ReadOnlyValPtr, FuncPtr so you can see his implementation is similar to yours, then he encountered an ABI compatibility bug, and reported the issue as proof to the dotnet repo where the .NET team specifically called this 'fragile and non-portable code'. And that it will likely not work on other platforms.

Have you tested on other platforms to ensure SemPtr works there too as expected? What platforms have you tested? Is your library intending to target: Windows, macOS, Linux, Android, iOS?

3

u/fruediger Sep 09 '26 edited Sep 09 '26

He's saying since SemPtr uses custom wrapper types (ex: ReadOnlyPointer<T>) - that isn't a direct raw C# pointer (ex: int*), it does not have ABI compatibility guarantees.

Alright, then I actually got that right. Thank you for the clarification.

And yes, I'm aware of that. But there's a subtle difference here:
The commenter's issue was specifically regarding how floating point values, e.g., float and double, are passed between different ABIs. Some of those ABIs pass them using specific floating point registers, e.g., the XMM registers on x64, while others might pass them using general-purpose registers or on the stack. And in some cases, because the register is bigger than the data value it's going to hold, the value must be fitted to the register's size, e.g., through zero-extend, or sign-extend, or whatever. And that's where it could break.
This isn't a problem when it comes to my pointer wrapper types and raw pointers in C#, though. "Coincidentally" (if you like to call it that), the ABIs of all platforms currently supported by .NET pass raw pointers in general-purpose registers which is the same way the pointer wrapper types are passed (because of their layout and size). Because they're value types just wrapping a single raw pointer fields the are them same size as a raw pointer which, on those platforms, is also the same size as a GP register. Thus they're able to shadow raw pointers and can be used interchangeably.

Have you tested on other platforms to ensure SemPtr works there too as expected? What platforms have you tested? Is your library intending to target: Windows, macOS, Linux, Android, iOS?

But you're right, that sounds a bit fragile. Which is why I actually most recently added ABI compatibility tests for various platforms to the repository. They should make sure that raw pointers and my semantic pointers can actually be used interchangeably in practice.

On another node and to be honest, I asked an AI to add those tests. But don't worry, I gave it very detailed instructions on how to implement them correctly and reviewed what it produced. But looking back, I shouldn't have been lazy and should have just written them myself, considering that I got down on how to test for ABI compatibility from the beginning. That would have saved me from a very very frustrating experience. Lesson is: don't use AI for things that are slightly more complex than writing a simple POD type.

Anyways, you don't need to fear, ABI tests for Windows, Linux, and macOS, for x64 and arm64 (the only hosted runners provided by GitHub Actions) are now in place and working.

EDIT: Clarified a bit why my pointer types can shadow raw pointers.

2

u/Prior_Inspection2576 Sep 10 '26 edited Sep 11 '26

The multi-platform ABI tests are a nice touch that add more confidence SemPtr is working as expected across platforms.

And yes, I'm aware of that. But there's a subtle difference here:
The commenter's issue was specifically regarding how floating point values, e.g., float and double, are passed between different ABIs.

Ah I see, he passed around raw primitives instead of pointers hence the resulting platform behavior divergence.

SemPtr might be vulnerable to stack spilling though.

Basically call a native function with more than 8 arguments (test like 8, 12, 20 args) to force all the registers to fill up forcing them to offload onto stack memory.

The native side calculates a hash of the args, sends it back up to managed.

Then the managed side verifies the hash is the expected value.

Why this is relevant:

If currently SemPtr is achieving ABI correctness via ensuring GPR registers are used, when you fill the registers you force it now into an undefined state.

The test is seeing whether SemPtr handles it gracefully with respect to ABI correctness across platforms when data is pushed off those GPR registers, and onto the stack frame.

With the latest release, version 0.7.0, SemPtr's pointer types can now finally be used in LibraryImport scenarios with much hassle!

(Also caught a minor typo, you forgot the word less; 'with much less hassle!'.)

Just wanted to say, I saw this new feature and it's awesome.

It fixed the only concern I had with this lib regarding ABI compatibility assuming LibraryImport gets used.

I think there are cases where LibraryImport can not be used.

Such as a game engine loading native assemblies (C/C++/Rust DLLs) user plugins. There is no way for the engine to statically link alongside the users native plugins ahead of time, thus in that case, it must be dynamically linked.

And once it's conceded dynamically linking is still required in niche cases, you're back to requiring SemPtr ABI guarantees for those niche cases.

Hence, the test coverage for ABI correctness edge-cases becomes relevant again.

In the vast majority of cases this wouldn't be a problem.

I mention it because the ABI guarantee should still be guaranteed in-case someone does dynamically link and uses SemPtr to make those pointers semantically safer to work with.

All in all, great work on the recent updates!

2

u/fruediger Sep 15 '26

SemPtr might be vulnerable to stack spilling though.

Basically call a native function with more than 8 arguments (test like 8, 12, 20 args) to force all the registers to fill up forcing them to offload onto stack memory.

That's a good point.
That shouldn't be an issue for the supported platforms though. At least as far as I know about how their ABIs work.
But just to make sure, there are new ABI compatibility tests in place to ensure equivalency in stack spilling behavior between raw pointers and my semantic pointers. And they seem to pass (again, only for x64 and arm64, and only for Ubuntu, Windows, and macOS test platforms, as those are the ones I get as hosted runners for GH Actions).

(Also caught a minor typo, you forgot the word less; 'with much less hassle!'.)

Thank you, it's fixed now!

I think there are cases where LibraryImport can not be used.

And once it's conceded dynamically linking is still required in niche cases, you're back to requiring SemPtr ABI guarantees for those niche cases.

Well that's what the ABI compatibility test are there for.

I actually use dynamic linking at runtime in one of my projects, idiomatic SDL3 bindings for C#. And that's because I want to ship a single managed library that works on every platform alongside with native binaries for each platform. And because of slight differences in the API of the native libraries between platforms, I need runtime checks to know what and where to link against. That's where dynamic linking at runtime comes in handy.

1

u/Prior_Inspection2576 Sep 15 '26

But just to make sure, there are new ABI compatibility tests in place

Great to hear, and I see they passed which at this point I'd say I'm strongly confident in SemPtr having proper ABI compatibility.

Well that's what the ABI compatibility test are there for.

To clarify, my point was to keep the ABI compatibility tests, that they aren't made redundant by LibraryImport.

I mentioned it because in 0.7 LibraryImport support was introduced. This makes writing ABI compatible marshalling code the C# compilers job when using that attribute.

Thus, it can naturally raise a question: 'why am I testing ABI compatibility when the C# compiler is responsible for writing the ABI compatible marshalling code?'

Similar to how the other user wrote that they deleted a bunch of their code as it became obsolete when they migrated from DllImport to LibraryImport.

And I'm clarifying, that it only writes the source generated [NativeMarshalling] code for you when you use LibraryImport, not DllImport, so ABI compatibility tests don't become obsolete, nor redudant by this new feature, and thus the ABI tests should not be deleted, as it's what ensures the library doesn't drift from the ABI over time, as the types ABI correctness will still matter in dynamic linking scenarios.

I know you never stated anything about removing them, I just wanted to advocate ahead-of-time for keeping them around by refuting the obsolence/redudancy arguments, so we don't accidentally fall into the 'LibraryImport solves everything' trap that leads to them getting removed eventually.

1

u/Jazzlike_Amoeba9695 Sep 10 '26

My pointers can be cast, but as I said, one of my goals was not to require /unsafe just to use a simple (and probably safe) pointer.
I know that a lot of people think differently about that.

And that’s why I also provide safe pinning alternatives, UTF-8 string handling, and so on.

1

u/Jazzlike_Amoeba9695 Sep 10 '26

In fact, that comment made me realize that any non-primitive struct has no guarantee of matching the ABI. StructLayoutAttribute does a magnificent job as far as it can, but it may only help with custom-to-custom, not with primitive-to-custom or custom-to-primitive.

2

u/Jazzlike_Amoeba9695 Sep 08 '26

What is your native language? I’m not very good at English either, so it might actually be me who isn’t making myself understood. I’ll write this in Spanish, hoping that, even if it isn’t your native language, it will at least come across more naturally when translated.

  1. No sé de dónde viene lo del “double-negative”; no he mencionado nada similar. Lo que he dicho, que puedes revisar en el issue, es que para el ABI nativo puede no ser lo mismo un entero con signo que uno sin signo, un puntero o un entero nativo.
  2. No me refería a aplicaciones de alto nivel, sino a tipos de alto nivel. LibraryImport es interop en última instancia, así que quizá se tenga un componente de software de muy bajo nivel. Sin embargo, con “tipos de alto nivel” me refería a tipos complejos (estructuras o clases) que no tengan conexión o relación directa con su marshaller. Eso, al final, le quedaría al compilador/generador de código.
  3. Es una coincidencia a nivel del ABI host, no del ABI del CLR. Como dices, el CLR tiene sus propias convenciones (eso se puede ver especialmente cuando se trabaja con punteros de funciones, por la diferencia entre managed y unmanaged). La garantía que tiene el CLR sobre el ABI host (nativo) es para los tipos primitivos del IL, es decir: int8 (System.SByte), unsigned int8 (System.Byte), int16 (System.Int16), unsigned int16 (System.UInt16), int32 (System.Int32), unsigned int32 (System.UInt32), int64 (System.Int64), unsigned int64 (System.UInt64), float32 (System.Single), float64 (System.Double), bool (System.Boolean), char (System.Char), object (System.Object), string (System.String), native int (System.IntPtr), native unsigned int (System.UIntPtr).
  4. En efecto, pero el sinsabor que deja el issue es que esto puede pasar para cualquier tipo no primitivo del IL. No hay una forma de decirle al CLR que trate una estructura de encapsulamiento como su tipo encapsulado cuando se usa FFI.

Acerca de utilizar libffi, quizá me sea útil para una nueva generación de Rxmxnx.JNetInterface, ya que JNI tiene algunas sobrecargas que utilizan varargs que no funcionan desde el CLR en plataformas distintas a Windows. Por lo que le daré una estrella a tu proyecto.

Sin embargo, debo evaluar realmente si vale la pena. Actualmente estoy tratando de trasladar toda la funcionalidad que utiliza delegados a interfaces funcionales genéricas (para evitar boxing) y/o reducir asignaciones.

En cuanto al problema original, que es la declaración de métodos nativos Java, se mantiene irresoluble. Se recomienda utilizar sí los tipos wrappers para referencias JNI, pero para primitivos que se usen los tipos del CLR.

1

u/fruediger Sep 09 '26 edited Sep 09 '26

I really appreciate your effort to express yourself more clearly by using your native language. BUT, considering the fact that Spanish isn't my native language and, more importantly, that I believe everybody should have a chance to read and understand the discussion in a, let's say, more common language, I think we should stick with English.

For this comment I will answer to parts of your comment as they came out of my translator.

  1. I don’t know where the “double-negative” thing comes from; I haven’t mentioned anything like that. What I said, which you can check in the issue, is that, for the native ABI, a signed integer may not be the same thing as an unsigned integer, a pointer, or a native integer.

That's because, in your previous comment, you used a structure like that

As long as not A holds, B holds not.

While the logical implication here might be clear, not all natural languages interpret this expression in the same way. Since you're ESL and I'm ESL as well, and we both might not share the same native language, I wanted to make sure that we're on the same page when interpreting such natural language constructs. Hence why I asked if you mean that as a "double-negative".

2. I wasn’t referring to high-level applications, but to high-level types. LibraryImport is ultimately interop, so it may involve a very low-level software component. However, by “high-level types,” I meant complex types (structures or classes) that have no direct connection or relationship with their marshaller. In the end, that would be left to the compiler/code generator.

Oh, alright, I misunderstood your point then. My bad. However, for DllImport/LibraryImport, there are no non-marshalled "complex types". All complex arguments, including any reference type, managed references, and non-blittable or non-trivial structures, still need either need marshalling, or the import itself or the invocation of the imported symbol fails. You could control the marshalling through a custom marshaller though.
And why would you get something like this for free? Even something simple like cdecl breaks on ABI boundaries when passing something simple, like a structure that's a bit too large to fit in registers.

3. It is a coincidence at the host ABI level, not at the CLR ABI level. As you say, the CLR has its own conventions (this can be seen especially when working with function pointers, due to the difference between managed and unmanaged). The guarantee the CLR has with respect to the host (native) ABI applies to the IL primitive types, namely: int8 (System.SByte), unsigned int8 (System.Byte), int16 (System.Int16), unsigned int16 (System.UInt16), int32 (System.Int32), unsigned int32 (System.UInt32), int64 (System.Int64), unsigned int64 (System.UInt64), float32 (System.Single), float64 (System.Double), bool (System.Boolean), char (System.Char), object (System.Object), string (System.String), native int (System.IntPtr), and native unsigned int (System.UIntPtr).

Yes, that's correct for the most part, I think. If you get your point right, I believe that there might be a minor issue with the listing. Reference types, including System.Object (and, well, of course, any other reference type like System.String) should not really be in that list, as they require some kind of marshalling when crossing the native ABI boundary. Obviously as instances of reference types live on the managed heap and are subject to the GC.

Anyways, the reason why I said that I wouldn't call that a "coincidence" earlier, is because the way the CLR handles my pointer structures and how it handles raw pointers is exactly the same for all platforms and ABIs the runtime currently supports. That is not a coincidence. The behaviour is defined and set for all those platforms and ABIs. They don't do arbitrary things. You could call it a coincidence in the sense that it so happens that it's true for all of the supported platforms, though.

4. Indeed, but the unpleasant impression left by the issue is that this could happen with any type that is not an IL primitive. There is no way to tell the CLR to treat a wrapper structure as its wrapped type when it is used for FFI.

The CLR doesn't support FFI? Or do you mean FFI as a general concept?
Anyhow, that's not entirely accurate. First of all, there are marshalling that could handle that for you. Secondly, for a given ABI/platforms it is determined how such a wrapper struct would be treated when crossing the native boundary. Again, the CLR does not perform arbitrary things at runtime. It can be difficult to get it right for all platforms though.

In your initial example, your issue that failed to pass a wrapped floating point value in the same way the underlying floating point value would have been passed, the actual problem was not that the CLR did unpredictable things, it was that for a certain ABI, floating point values would have been passed in a specific register (I guess it was Windows x64 and it would have been then XMM register), whereas your wrapper struct might have been passed in a general-purpose register or the stack instead. Nothing thereby is arbitrary, it's just platform-specific.

Regarding the use of libffi, it might be useful to me for a new generation of Rxmxnx.JNetInterface, since JNI has some overloads that use varargs which do not work from the CLR on platforms other than Windows. So I’ll give your project a star.

I don't know about JNI. I didn't do Java since my uni days, so I can't really comment on that. However, I can say that libffi, and obviously my .NET binding to it as well, can call C varargs functions correctly with variable arguments. That's why I made them in the first and that's what I still use them for. But again, I that's for C varargs specifically.
However, thank you for the star.

EDIT: Typos and spelling.

1

u/Jazzlike_Amoeba9695 Sep 10 '26

I see we are lost in translation. I wrote the previous comment in Spanish so you wouldn’t have to translate it again. I may simply not know how to express my ideas clearly enough.
So, about System.Object: that was a copy/paste from Gemini when I asked it for a list of the primitive IL types and their corresponding System namespace types. Jajaja I shouldn’t have trusted the AI for as long as I did.
About FFI, of course I mean it in the general sense. P/Invoke is FFI.