4

Is there a way I can develop a sample C# program, and make it a DLL, and use it in my C program?

Say, C# DLL has a function add(int a, int b) which returns or prints the result. I want to use this in my C program. Any example link should be a good help.

2
  • I made it work for c++, donot understand how to use in C, Couldn't find a way to make it work. Using it in C is the key challege for me Commented Nov 30, 2010 at 13:17
  • example code from YOU of what you've already tried should be a good help. Commented Nov 30, 2010 at 15:23

2 Answers 2

6

The easiest way to do this is to expose the C# DLL as a COM object, and then create an instance of it from your C/C++ application. See MSDN for a step-by-step guide.

Alternatively, if it's actually a C++ application that you want to be able to call the C# DLL from, you could create a mixed-mode C++/CLI application, which contains both managed and unmanaged code. The C++ application can then call functions directly from the managed C# DLL.

Also see "An Overview of Managed/Unmanaged Code Interoperability" on MSDN.


EDIT: Without any more information than "it doesn't work in C," I don't even know which of the above suggestions that you tried. As I suggested, I'm not certain if the second will work with straight C (never tried it), but I see no reason why the first wouldn't.

Regardless, the quick and dirty fix might be to wrap the C# functions in a C++ DLL, which you then call from your C application. Make sure that you declare any of the functions that you want to export from the C++ DLL as extern, otherwise their names will be mangled C++ names, which are impossible to work with in C. See here for more information: http://www.parashift.com/c++-faq-lite/mixing-c-and-cpp.html

Sign up to request clarification or add additional context in comments.

1 Comment

I made it work for c++, donot understand how to use in C, Couldn't find a way to make it work. Using it in C is the key challege for me.
0

Here is a solution. The solution provides [DllExport] attribute that aallows to call C# function from C.

https://sites.google.com/site/robertgiesecke/Home/uploads/unmanagedexports

C# code

class Test
{
     [DllExport("add", CallingConvention = CallingConvention.StdCall)]
     public static int Add(int left, int right)
     {
         return left + right;
     } 
}

C code

 int main()
 {
      int z = add(5,10);
      printf("The solution is found!!! Z is %i",z);
      return 0;
 }

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.