How to call a c++ function from c# program

psri1248's Avatar, Join Date: Feb 2008
Newbie Member
Hi,

Can any of you, tell me how to call c++ functions from c# program?

I have a C++ dll, in which i have some functions, now i want to call them from my c# code. Please tell me how can i do this. If possible provide me sample code n all.

Thank you in advance

Bye,
sree
0
SaswatPadhi's Avatar, Join Date: May 2009
~ Б0ЯИ Τ0 С0δЭ ~
[ Late reply, but this may help others ]

Well, I think that should not be too difficult. You can use DllImport.

Say you have the following C++ func in a dll :
Code: c++
// int Sum (int, int) inside MyDll.dll
int Sum(int x, int y)
{      return x + y;      }
and you want to use it in your C# app.

So, you can use it like this :
Code: c#
using System;
using System.Collections.Generic;
using System.Text;
using System.Runtime.InteropServices; //For "DllImport"

namespace MyCSharp
{
      class Program
      {
      [DllImport("MathFuncsDll.dll", CharSet = CharSet.Auto)]
      public static extern Int32 Sum(Int32 a, Int32 b);

            static void Main()
            {
                  Console.WriteLine(Sum(3, 4));
            }
      }
}

Simple, isn't it ?


PS : Just embed a manifest to avoid the error : "An application has made an attempt to load the C Runtime library without using a manifest."
0
shabbir's Avatar, Join Date: Jul 2004
Go4Expert Founder
Very well explaind Saswat and also for creating the DLL you can refer to Creating a simple DLL
0
SaswatPadhi's Avatar, Join Date: May 2009
~ Б0ЯИ Τ0 С0δЭ ~
Quote:
Originally Posted by shabbir View Post
Very well explaind Saswat and also for creating the DLL you can refer to Creating a simple DLL
Thanx both for the article and the compliment !