Per Erik Strandberg /cv /kurser /blog

Combining C# and C (ansi)

To combine the best from both worlds - using for example a native dll written in C in your brand new .NET application is really easy, the tricks are to use "__declspec(dllexport) __stdcall" in C and "DllImport" in C#.

The C-code

What we need to do is a C-dll that exposes a method to external viewer, here sayHello(int N) that prints a small hello on The Console.

Copy the below code into a file called for example "sayHello.c".

#include <stdio.h>
#include <stdlib.h>
#include <string.h>

void __declspec(dllexport) __stdcall sayHello(int N)
  printf("C  >> hello nr '%d'\n", N);

Compile it, for example with cl, into a dll: cl sayHello.c /LD /Zi.

The C# code

In C# we create a small application that prints start and stop on the console. Also we need to import from dll using the command "DllImport".

I pretty much guess that extern (dll-imported) methods have to be static, but they most certainly do not need to return void.

Once we've imported it - we can use it any time. Here I call it with 314.

Copy the below code into a file called "main.cs".

using System;
using System.Text;
using System.Runtime.InteropServices;

class ccc
  [DllImport("sayHello.dll")] extern static void sayHello(int N);

  static void Main(string[] args)
    Console.WriteLine("C# >> start");
    Console.WriteLine("C# >> stop");

Compile the *.cs-file to an executable: csc.exe main.cs.

Enjoy the output

Three lines of output should be printed on The Console - the first and last can be seen in the .cs-file. The middle one is the most interesting: Here we call the method sayHello(). Since this one is declared in our C# class the compiler accepts it as long as we use it like we declared it. In runtime the system then looks for the dll. First in the same folder, then in the path.

If a dll is found with the correct name the system checks it for a method with the signature "sayHello(int)" (although it does not have to be an int - as long as it has the same number of bytes as an integer). If such a method is found it is called. And voila: "C >> hello nr '314'" is printed on The Console.

C# >> start
C  >> hello nr '314'
C# >> stop

See also

Python Cansi Combo.

This page belong in Kategori Programmering.