How do you call unmanaged code in C#?

πŸ’‘ Concept: Calling Unmanaged Code from C#

Sometimes, C# alone isn’t enough. Maybe you need to use a Windows API that .NET doesn’t expose, or you want to reuse a fast old C++ library. That’s where unmanaged code comes in β€” code that runs outside the .NET runtime. In C#, we connect to it using something called P/Invoke.

πŸ“˜ Quick Intro

P/Invoke (Platform Invocation Services) is like a bridge 🚧 between the .NET world and native libraries. It lets your C# methods call functions inside unmanaged DLLs without rewriting them in C#. You just declare the function signature in C#, and .NET takes care of talking to the native side.

🧠 Analogy

Imagine you’re making an international phone call πŸŒπŸ“ž. - You (C# code) speak one language. - The person abroad (unmanaged code) speaks another. - The gateway operator (P/Invoke) translates everything in real time. If the translation is accurate (correct function signature + data types), the call is smooth. If not, you’ll get gibberish… or the call will drop. That’s exactly how P/Invoke works β€” a translator between two different worlds.

πŸ”§ Technical Breakdown

  • πŸ“₯ DllImport: Use the [DllImport] attribute to point to the DLL and define the function you want to call.
  • πŸ› οΈ Marshaling: .NET converts your C# types (like string, int) into native equivalents that C/C++ expects.
  • πŸ’» Interop: Works with native C, C++, and Win32 APIs (like user32.dll or kernel32.dll).
  • ⚠️ Gotchas: Memory leaks and crashes can happen if you mis-declare the function or forget to free unmanaged resources.
  • πŸ“Œ Example: Calling the classic Windows MessageBox function:
    
    [DllImport("user32.dll", CharSet=CharSet.Auto)]
    public static extern int MessageBox(IntPtr hWnd, string text, string caption, int type);
    
    // Usage
    MessageBox(IntPtr.Zero, "Hello from unmanaged world!", "Interop Demo", 0);
    

🎯 Real-World Use Cases

  • βœ… Reusing old but battle-tested C/C++ libraries in modern .NET apps.
  • βœ… Calling OS-level APIs (like Windows system dialogs, file operations, etc.).
  • βœ… Speeding up performance-critical operations by offloading to native code.
  • βœ… Talking to external hardware or drivers that only provide C APIs.

πŸ’» Code Example


using System.Runtime.InteropServices;

class Program {
    [DllImport(""user32.dll"", CharSet = CharSet.Unicode)]
    public static extern int MessageBox(IntPtr hWnd, string text, string caption, int options);

    static void Main() {
        MessageBox(IntPtr.Zero, ""Hello from unmanaged code!"", ""P/Invoke Example"", 0);
    }
}

❓ Interview Q&A

Q1: What is unmanaged code?
A: Code not managed by the CLR.

Q2: What is P/Invoke?
A: Platform Invocation to call unmanaged DLL functions.

Q3: How do you specify the DLL?
A: Using DllImport attribute.

Q4: What are marshaling concerns?
A: Converting data between managed and unmanaged memory.

Q5: Can you call C++ code?
A: Yes, if exposed via C-style DLL exports.

Q6: Is memory management automatic?
A: No, must be handled carefully.

Q7: Can P/Invoke cause crashes?
A: Yes, if used incorrectly.

Q8: Is P/Invoke supported on all .NET platforms?
A: Mostly, but some restrictions exist.

Q9: Alternatives to P/Invoke?
A: COM Interop, C++/CLI.

Q10: Why call unmanaged code?
A: For legacy or performance reasons.

πŸ“ MCQs

Q1. What is unmanaged code?

  • Code outside CLR management
  • Managed code
  • C# code
  • Java code

Q2. What is P/Invoke?

  • Calling managed code
  • Calling unmanaged DLLs
  • Debugging
  • Profiling

Q3. How to specify DLL?

  • DllImport attribute
  • Marshal class
  • Namespace
  • Assembly info

Q4. What is marshaling?

  • Memory allocation
  • Data conversion
  • Thread management
  • Garbage collection

Q5. Can P/Invoke call C++?

  • No
  • Yes
  • Sometimes
  • Rarely

Q6. Is memory management automatic?

  • Yes
  • No
  • Sometimes
  • Rarely

Q7. Can P/Invoke cause crashes?

  • No
  • Yes
  • Maybe
  • Never

Q8. Is P/Invoke on all .NET platforms?

  • No
  • Mostly
  • Yes
  • Sometimes

Q9. Alternatives to P/Invoke?

  • COM Interop
  • Reflection
  • Serialization
  • Attributes

Q10. Why call unmanaged code?

  • For fun
  • Legacy or performance
  • Testing
  • Debugging

πŸ’‘ Bonus Insight

Calling unmanaged code bridges legacy native libraries with modern .NET applications, enabling powerful integrations.

πŸ“„ PDF Download

Need a handy summary for your notes? Download this topic as a PDF!

πŸ” Navigation

Learn More About C# πŸ“š

1. What is C#? πŸ‘‰ Explained
2. Main Features of C# πŸ‘‰ Explained
3. Difference Between C# and Java πŸ‘‰ Explained
4. Common Language Runtime (CLR) in C# πŸ‘‰ Explained
5. Common Type System (CTS) in C# πŸ‘‰ Explained
6. Common Language Specification (CLS) in C# πŸ‘‰ Explained
7. Value Types vs Reference Types in C# πŸ‘‰ Explained
8. What is a Namespace in C#? πŸ‘‰ Explained
9. Purpose of the 'using' Keyword in C# πŸ‘‰ Explained
10. Different Data Types in C# πŸ‘‰ Explained
11. Difference Between int and Int32 in C# πŸ‘‰ Explained
12. Difference Between float, double, and decimal in C# πŸ‘‰ Explained
13. What is the Default Value of a Boolean in C#? πŸ‘‰ Explained
14. What is Boxing and Unboxing in C# πŸ‘‰ Explained
15. What are the Different Types of Operators in C# πŸ‘‰ Explained
16. Difference Between Equals and == in C# πŸ‘‰ Explained
17. What is the Null-Coalescing Operator ?? in C# πŸ‘‰ Explained
18. What is the Ternary Operator in C# πŸ‘‰ Explained
19. How Does the Switch Statement Work in C# πŸ‘‰ Explained
20. What is Object-Oriented Programming in C# πŸ‘‰ Explained
21. What are the Four Pillars of OOP in C# πŸ‘‰ Explained
22. What is Encapsulation in C# πŸ‘‰ Explained
23. What is Inheritance in C# πŸ‘‰ Explained
24. What is Polymorphism in C# πŸ‘‰ Explained
25. What is Abstraction in C# πŸ‘‰ Explained
26. What is an Abstract Class in C# πŸ‘‰ Explained
27. What is an Interface in C# πŸ‘‰ Explained
28. Can a Class Implement Multiple Interfaces in C#? πŸ‘‰ Explained
29. Difference Between Abstract Class and Interface in C# πŸ‘‰ Explained
30. How Do You Create a Class in C#? πŸ‘‰ Explained
31. What is a Constructor in C# πŸ‘‰ Explained
32. What Are the Types of Constructors in C# πŸ‘‰ Explained
33. What is a Static Constructor in C# πŸ‘‰ Explained
34. Difference Between Static and Non-Static Members in C# πŸ‘‰ Explained
35. What is the Use of 'this' Keyword in C# πŸ‘‰ Explained
36. What is a Destructor in C# πŸ‘‰ Explained
37. What is Object Initializer Syntax in C# πŸ‘‰ Explained
38. What is the Difference Between Field and Property in C# πŸ‘‰ Explained
Share:

Tags:


Feedback Modal Popup