#platforminvoke

💾 Paweł Łukasikpawel_lukasik@infosec.exchange
2024-04-19

In the last two posts, we learned how we could use native libraries. When searching for a library to load, a few candidates are checked before it throws a DllNotFoundException.

If we specify in the code that we would like to load "test" 1️⃣, it will check a couple more: test.so, libtest.so, and test. We can see those in the exception output if the resolution fails 3️⃣. Only after all of those are not found will it throw an exception, causing our application to crash.

If needed, we can also attach our own resolver using NativeLibrary.SetDllImportResolver 2️⃣, which allows us to perform the resolution ourselves. One resolver per assembly can be registered with this method.

Docs 📑: learn.microsoft.com/en-us/dotn

#dotnet #platforminvoke #libraryimport #librarynameresolution
---
If you find this useful, consider giving a like & share ♻

C# code using name resolution.
💾 Paweł Łukasikpawel_lukasik@infosec.exchange
2024-04-18

P/Invoke does allow linking with unmanaged libraries, but it does not work correctly with trimming and ahead-of-time compilation, which are key features of building performant .NET libraries. To mitigate this, a new attribute was introduced - LibraryImportAttribute.

LibraryImport is similar to DllImport with a few exceptions. The method should be partial instead of extern, and we can provide both the library name and the method name. Dealing with string types requires adding information about marshaling to correctly map the value.

One important thing to note is that the project must be marked with AllowUnsafeBlocks.

Docs 📑: learn.microsoft.com/en-us/dotn

#dotnet #platforminvoke #libraryimport
---
If you find this useful, consider giving a like & share ♻

C# code using LibraryImport attribute
💾 Paweł Łukasikpawel_lukasik@infosec.exchange
2024-04-17

P/Invoke is a way to allow unmanaged libraries from managed code. In the old days, it was a way to access Windows API that was not yet available in the .NET framework.

Since .NET became multi-platform, being present on Mac and Linux, P/Invoke has also been available on those platforms.

To import a native method that we would like to use, we need to create a static extern function and mark it with the DllImport attribute.

The DllImport attribute allows us to specify the native library from which the function should be loaded, as well as some extra parameters to cover more complex scenarios.

Docs 📑: learn.microsoft.com/en-us/dotn

#dotnet #platforminvoke #pinvoke
---
If you find this useful, consider giving a like & share ♻

C# code using p/invoke.

Client Info

Server: https://mastodon.social
Version: 2025.04
Repository: https://github.com/cyevgeniy/lmst