Go4Expert

Go4Expert (http://www.go4expert.com/)
-   C# (http://www.go4expert.com/forums/c-sharp/)
-   -   How to call a c++ function from c# program (http://www.go4expert.com/forums/cpp-function-c-sharp-program-t9699/)

psri1248 2Apr2008 14:32

How to call a c++ function from c# program
 
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

SaswatPadhi 14May2009 17:57

Re: How to call a c++ function from c# program
 
[ 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: 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."

shabbir 14May2009 18:38

Re: How to call a c++ function from c# program
 
Very well explaind Saswat and also for creating the DLL you can refer to Creating a simple DLL

SaswatPadhi 14May2009 18:41

Re: How to call a c++ function from c# program
 
Quote:

Originally Posted by shabbir (Post 47816)
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 ! :smile:


All times are GMT +5.5. The time now is 08:05.