MichalStrehovsky / zerosharp

Demo of the potential of C# for systems programming with the .NET native ahead-of-time compilation technology.
2k stars 103 forks source link

String marshalling with noruntime #23

Closed ZeroLP closed 2 years ago

ZeroLP commented 2 years ago

As I was delving myself with building a simple driver with the combination of samples of noruntime and noruntime-efi, I was a bit stranded with having to marshal C# string to for case of to a c string (LPCSTR). Would it even be possible to marshal without a runtime? If it is, any suggestion or an idea of how to approach this issue?

Linking my project here for a more visual reference: https://github.com/ZeroLP/ZeroKernel (Hopefully I'm not violating any OSP license since I can't really find it in the official repo if there is one)

ZeroLP commented 2 years ago

Solved it by abstractly having a null-terminated string and by pointing the char* into the pinvoke argument. Although I would like to know if there is another way of doing so. (As far as my theoretical knowledge goes, I can't figure out other than what I've done)

MichalStrehovsky commented 2 years ago

You can consider the source/project files in this repo public domain.

You can marshal things manually this way:

https://github.com/MichalStrehovsky/zerosharp/blob/aedf1318b8a2cbc1ec8f990c4cbd66f28129f491/no-runtime/zerosharp.cs#L131-L138

But since you're on Windows, consider calling into the W versions of APIs instead of the A variants - the *W expect null-terminated UTF-16, which happens to match how strings are laid out in .NET.

If you do that, you can just pass them with the fixed keyword like it's done here:

https://github.com/MichalStrehovsky/zerosharp/blob/aedf1318b8a2cbc1ec8f990c4cbd66f28129f491/no-runtime/zerosharp.cs#L129