This library is designed to allow users of all .NET languages to be able to use pointers without trouble, just like those using C# or C++. Of course, it will be at the user's own risk.
Using the code
I was bothered by the fact that pointers (and related operations) can only be accessed in C# and C++, and that they only work on unmanaged types. I then decided to make a library which would overcome this, because:
- certain P/Invoke methods need it,
- because languages other than C++ and C# do not support pointers, and
- because the pointer structure is now strongly typed.
Just beware that using the
Marshal class may be more accurate than this library, because the methods are for managed types (before marshaling). I noticed this only after I made the library. But, hey, if it works, use it!
Points of interest
ManagedSizeOf<T>() returns the same thing as saying
sizeof(T) in C#, only that it is not restricted to unmanaged types - if
T is a reference type, it returns the size of the reference (which on x86 computers seems to be 4 bytes). If
T is a value type, it returns the size of that type, whether or not it is managed. The reason that I put the word Managed in front of it was to indicate that it returns the size of the type before marshaling, unlike
ManagedSizeOf(System.Type type) method uses Reflection to call the other
ManagedSizeOf method, while substituting
T with the type. Therefore, it is inherently slower than the previous method and should be used with care.
GetAddressOf<T>(ref T obj) method returns the address of that variable, whether or not it is a reference type.
Pointer<T> structure encapsulates a variable of type
T* which can be indexed like normal pointers (like
ptr), as well as converted to
System.IntPtr and other formats. If the language supports pointers (like in C#), then the pointer field can be directly used. Otherwise, indexing and other properties must be used, or it can be converted to a
Here is a bug I found, but do not know how to fix (any suggestions are appreciated): on one computer (on which I was not an Administrator), a test program was run. However, a
VerificationException occurred before entering
Main, because the runtime could not verify the code in UnsafeLibrary.dll. I only saw this error once.
This program may have bugs.. don't rely on it being correct! Tell me if you find any. I am still not sure whether the
AddressOf method works correctly all the time, because I do not know whether it returns the address of the
ref parameter or a copy of it.