Is there a way to call a C function in C#?

Asked

Viewed 310 times

2

Let’s say I have a library with a C function, which was compiled using gcc, there is how to call this function in C#, if yes what would be the performance of it compared to the same function created in C#?

  • 1

    You can’t measure performance because in the question you didn’t add the corresponding function code, and I’m in doubt about what you want. Vc want to measure the performance of a function in C or vc need to call a function in C through C#?

  • It is a generic function whatever runs a loop for example of 65,000 times and returns me some value, if by chance C managed to run at a rate faster than C# would if more practice to use a function in C than C#, it was clear.

1 answer

4


First you have to export the function in your C.

For example

//Exemplo.dll
extern "C" __declspec(dllexport) double funcaoExemplo (int valor)
{
   //código
}

and in your C# you should use the Dllimport

   [DllImport("Exemplo.dll")]
   private static extern double funcaoExemplo (int valor);

   public double Teste (int value)
   {
      return funcaoExemplo(value);
   }

In relation to performance C has an advantage over this aspect, because C is a language compiled, while C# is a language semi-compiled, that dependent on the framework.

  • In the case when the C function is called it will not suffer any influence from the right . NET platform?

  • Only on call, because of Dllimport, but not during "method execution"

  • 1

    The answer is incomplete. To export a symbol in a dll you need to use "__declspec(dllexport)". The example of the answer looks like this: extern "C" __declspec(dllexport) double function).

  • Thank you @Joséx. I will correct!

  • Note that if the c++ dll is compiled on a different architecture than the c#program, it may give Runtime error.

Browser other questions tagged

You are not signed in. Login or sign up in order to post.