1. This site uses cookies. By continuing to use this site, you are agreeing to our use of cookies. Learn More.

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

Discussion in 'C#' started by psri1248, Apr 2, 2008.

  1. psri1248

    psri1248 New Member

    Joined:
    Feb 8, 2008
    Messages:
    3
    Likes Received:
    0
    Trophy Points:
    0
    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
     
  2. SaswatPadhi

    SaswatPadhi ~ Б0ЯИ Τ0 С0δЭ ~

    Joined:
    May 5, 2009
    Messages:
    1,343
    Likes Received:
    55
    Trophy Points:
    0
    Occupation:
    STUDENT !
    Location:
    Orissa, INDIA
    Home Page:
    [ Late reply, but this may help others :smile: ]

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

    Say you have the following C++ func in a dll :
    Code:
    // 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:
    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."
     
    shabbir likes this.
  3. shabbir

    shabbir Administrator Staff Member

    Joined:
    Jul 12, 2004
    Messages:
    15,283
    Likes Received:
    364
    Trophy Points:
    83
  4. SaswatPadhi

    SaswatPadhi ~ Б0ЯИ Τ0 С0δЭ ~

    Joined:
    May 5, 2009
    Messages:
    1,343
    Likes Received:
    55
    Trophy Points:
    0
    Occupation:
    STUDENT !
    Location:
    Orissa, INDIA
    Home Page:
    Thanx both for the article and the compliment ! :smile:
     

Share This Page