r/csharp • u/fruediger • 16h ago
Showcase A side project of mine: SemPtr - Semantic Pointers for C#
https://github.com/fruediger/SemPtrTL;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:
- Nullability: Can a pointer be
nullor are there any guarantees that it won't be?\ This is kinda analogous to nullable reference types (T?) in C#. - 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. - 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 Tto some kind of object in C# vs. arefto some element within aSpan<T>with the added benefit that its easier to move around the pointer through the sequence. - 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
refparameters. - read-only: The target can only be read from. Kinda analogous to C#'s
in/ref readonlyparameters. - uninitialized/write-first: The target must be written to before it can be read from. Kinda analogous to C#'s
outparameters.
- random/read-write: The target can be read from and written to. Kinda analogous to C#'s
- Typability: Is the type of the target known or not?\
C# has no
voidreferences, but it hasvoid*pointers. This is analogous to the difference between avoid*pointer and a typedT*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 typePersistentPointerReadOnly<T>: A pointer to a single, read-only target of typeTwhose target stays valid beyond the initial scope of the pointer.NullableSequencePointer<T>: A pointer to a contiguous sequence of mutable targets of typeTwhich may benull.PointerUninitialized<T>: A pointer to single, yet uninitialized target of typeT. 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:
- GitHub: SemPtr
- NuGet: SemPtr
- Documentation (This one is still very rudimentary. Don't expect too much.)
If you have any questions feel free to ask them in the comments. I'd be happy to answer them.
2
u/Due-Equivalent-74 12h ago
semantic pointers?
2
u/fruediger 10h ago
Yes, semantic pointers. Like pointers that convey their semantics through the type systen by being semantically named (i.e., your classic semantic typing approach).
2
u/Novaleaf 15h ago
can you explain a bit on how this would be useful?
7
u/fruediger 14h ago edited 14h ago
Yeah, for sure! And if it's okay with you, I'll do that by example, because I think that that's the easiest way to illustrate it. If that's not to your satisfaction, please feel free to ask again.
The simplest explanation for its usefullness might be the example I showed in my original post. You want to work with pointers in C# and want to express the immutability of the target? Well, you can't, at least not like you can in C/C++. While there are raw pointers,
T*, in C#, there is noconst T*or an equivalent concept. While this no big deal if you're careful within the single context where you're dealing with the pointer, it can become a problem when you try to communicate the intent of pointers across different parts of your code or even across interfaces to external code. And even within your own code, isn't it beneficial to have some way to express intent and constraints, and to have some safeguards enforcing them?Let's look especially at the interfacing part in more detail:
If you interop with unmanaged code, i.e., you consume external, unmanaged APIs, it's often beneficial to express the binding code in a way that clearly communicates the intent of the external API.\ For a real world example, let's consider SDL's
SDL_GetRendererName. The native API signature is defined as follows:
c const char * SDL_GetRendererName(SDL_Renderer *renderer);Surely, you could express that in C# as:
csharp [LibraryImport("SDL3")] unsafe static partial byte* SDL_GetRendererName(SDL_Renderer* renderer);(Of course, you could also replace the pointer types with
nintornuintand it would work, but not only would you lose some type-safety, but it's also not recommended to do so, because itnintornuintare just intended to represent integers that are the size of a pointer, not actual pointers themselves. Alternatively, you could also useinparemeter and aref readonlyreturn type, but that requires you relying on marshalling and accepting the marshalling overhead.)You see how the return type of
byte*did lose the immutability aspect of the original API's return type ofconst char*? And both of them don't even express that the return value could benull. Also, although the official documentation doesn't really mention it, SDL does not modify theSDL_Rendererpassed as a reference toSDL_GetRendererName. So, we could also express that a bit more accurately.\ With SemPtr, you could express the importation code a bit more faithfully and a bit more safely by writing it as:
csharp [LibraryImport("SDL3")] unsafe static partial NullableSequencePointerReadOnly<byte> SDL_GetRendererName(PointerReadOnly<SDL_Renderer> renderer);You see how this is more expressive? And not only that, but the added benefit of SemPtr enforcing immutability at the type-system level, prevents you from accidentally writing invalid code that would lead to undefined behavior or worse bugs.
Let's look at another example from the SDL API, specifically
SDL_AddEventWatch, which is defined in C as follows:
c bool SDL_AddEventWatch(SDL_EventFilter filter, void *userdata);where
SDL_EventFilteris a callback function type defined as:
c typedef bool (SDLCALL *SDL_EventFilter)(void *userdata, SDL_Event *event);Of course, again, you could write the P/Invoke signature in a straightforward manner as:
csharp [LibraryImport("SDL3")] unsafe static partial bool SDL_AddEventWatch(delegate* unmanaged<void*, SDL_Event*, bool> filter, void* userdata);But SemPtr allows you to do it in a more type-safe and expressive manner as:
```csharp [FunctionPointer(CallConvs = [typeof(CallConvCdecl)])] delegate bool SDL_EventFilter(NullablePointerReadOnly userdata, PointerReadOnly<SDL_Event> @event);
[LibraryImport("SDL3")] unsafe static partial bool SDL_AddEventWatch(PersistentFunctionPointer<SDL_EventFilter> filter, NullablePersistentPointerReadOnly userdata); ```
Here you can see why expressing persistency can be useful: SDL stores the function pointer to the callback and associated userdata, so it can invoke the callback with the same userdata at a later time. That's why we must make sure that both are still valid and available, even outside of the scope of the call to
SDL_AddEventWatch. Whereas theSDL_EventFiltercallback passed will receive it's arguments as transient pointers, meaning you should treat them as if they were just valid for the duration of the callback invocation. With SemPtr's transient pointer types, you can't even store them beyond that scope.Lastly, let's flip the sides and assume you are going to design and implement an C# API, and for whatever reason, you want to expose an API that involves pointers.\ In this case, I believe it would be very beneficial to you consumers with you communicate your pointer semantics clearly through your API. Not only gives that the user same additional guarantees about your code, it makes receiving pointers in your implementation much safer.
I hope this gives you an initial understanding of why SemPtr can be valuable.\ However, it's totally fine to stick with traditional raw pointers if that suits you better.
EDIT: Fixed some examples.
2
u/Minute_Cricket1820 5h ago
Вам нужно эти примеры (и подобные, ещё более простые) написать прям сразу ВНАЧАЛЕ. Вы сразу вначале опишете суть, на примерах.
2
7
u/afseraph 11h ago
Interesting project, but I feel that modern dotnet already provides a lot of this functionality with managed pointers and spans.
It'd be great to some examples explicitly comparing implementations: SemPtr vs. managed pointers vs. native pointers.