how to call c code in csharp

To call C code in C#, you need to use Platform Invoke (P/Invoke) to interact with an unmanaged library. Here are the steps:

  1. Create a C library: You need to create a dynamic link library (DLL) written in C that exposes functions that you want to call in C#. Make sure to export the functions using __declspec(dllexport).
#include <stdio.h>

__declspec(dllexport) void printHelloFromC()
{
    printf("Hello from C!\n");
}
100 chars
7 lines
  1. Build the C library: Compile the C code and create a DLL.

  2. Import the C library into C#: You need to declare the C function using the DllImport attribute.

main.cs
using System.Runtime.InteropServices;

class Program
{
    [DllImport("myclib.dll")]
    public static extern void printHelloFromC();

    static void Main(string[] args)
    {
        printHelloFromC();
    }
}
212 chars
13 lines
  1. Run the C# console application: Run the C# console application, and you should see the message "Hello from C!" printed in the console.

Note: Make sure to use the correct calling convention and data types when declaring the C function in C#.

gistlibby LogSnag