Search code examples
c#clrunsafe

Why unsafe context is not required to call C functions from C# program?


I recently started working on C# programming(I worked only on C before). I came to know that we need to use unsafe context to use pointers in C# program as Microsoft docs page.

One of the advantages of not using pointers are

Using unsafe code introduces security and stability risks.

But we don't need to use unsafe context to call functions in C which may contains poorly written code or security vulnerabilities. Common Language Runtime Can't detect problems in these C functions.

These are my questions

  1. Why it is not required to use unsafe context to execute functions written in C even though CLR can't detect problems in these code?

  2. What may be the advantage of not using the unsafe context for calling functions written in C?


Solution

  • Why it is not required to use unsafe context to execute functions written in C even though CLR can't detect problems in these code?

    Unsafe mode isn't about the method being called that is unsafe, C# code can be equally unsafe. Unsafe mode is about the memory management which is bypassed. If you allocate variables though the CLR (so managed), which are passed to C++ libraries, like the Win32 libraries, the CLR can still manage the memory segments used, since they are still CLR variables.

    What may be the advantage of not using the unsafe context for calling functions written in C?

    If you don't need unsafe memory allocation, there is no point in using an unsafe context.