Call C code in C#
Cross-language calls, especially calling external libraries from .NET languages (such as C#) and code written in different programming languages, are often a challenge. This article explores how to call C code in C#, specifically from code library files (*.dll).
Solution: C/CLI wrapper assembly
An effective solution is to use C/CLI, a language extension that connects C and the .NET Framework. C/CLI allows seamless interaction between unmanaged C code and managed code such as C#.
Create a C/CLI wrapper assembly to expose the functionality of the required C code. This wrapper acts as an intermediary, allowing C# code to call the C implementation as if it were C# code.
Example: RakNet Network Library
To illustrate this approach, consider using the RakNet network library. Compile the following C/CLI code by using the /clr switch:
<code class="language-c++">#include "NativeType.h" public ref class ManagedType { NativeType* NativePtr; public: ManagedType() : NativePtr(new NativeType()) {} ~ManagedType() { delete NativePtr; } void ManagedMethod() { NativePtr->NativeMethod(); } }; </code>
You can create a managed assembly that can be referenced in C# code. This allows you to access C functionality via the ManagedType class:
<code class="language-c#">ManagedType mt = new ManagedType(); mt.ManagedMethod();</code>
Summary
By leveraging C/CLI, you can effectively extend the functionality of the .NET language by interacting with C code. This approach simplifies the integration of external libraries and enables smooth interaction between different programming environments.
The above is the detailed content of How Can I Call C Code (DLL) from C#?. For more information, please follow other related articles on the PHP Chinese website!