Pages

Thursday, 30 September 2021

Windows Tech Series: How to call C funtions in a DLL from C#

 1 Simplest example code


using System;
using System.Runtime.InteropServices;

namespace WaveApiTestCS
{
    class Program
    {
        static void Main(string[] args)
        {
            Console.WriteLine(Add(2,3));
            Console.ReadLine();
        }

        [DllImport("mydll.dll")]
        static extern Int32 Add(Int32 a, Int32 b);
    }
}

Details of how to generate "mydll.dll" can be found on another blog.

2 Traps

The C# project must be compiled against the same "Platform" as the DLL being used.

E.g. if mydll.dll is an x86-32bits DLL, the C# must be compiled against x86 as well.

C# Project --- Properties --- Build --- General --- Platform target = "x86".

Otherwise, an exception "System.BadImageFormatException" will be thrown out.

No comments:

Post a Comment