How to use existing C # code from C program

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

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

+4
source share
2 answers

The easiest way to do this is to show the C # DLL as a COM object, and then create an instance from your C / C ++ application. See MSDN for a walkthrough.

Alternatively, if this is actually a C ++ application that you want to call the C # DLL with, you can create a mixed C ++ / CLI application that contains both managed and unmanaged code. A C ++ application can then call functions directly from a managed C # DLL.

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


EDIT: Without more information than โ€œit doesn't work in Cโ€, I donโ€™t even know which of the above suggestions you tried. As I suggested, I'm not sure that the second will work with direct C (never tried), but I see no reason why the first will not.

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

+6
source

Here is the solution. The solution provides the [DllExport] attribute, which allows you to call the 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; } 
0
source

All Articles