Call C code from managed code

I currently have a C function that I would like to use in .NET (C #).

I see two ways to achieve this:

  • Compilation (I think it's possible) from / clr to VC ++. NET by implementing managed facade methods that invoke C code.

  • Compiling C code as a DLL, and then calling the API.

What do you find best? How to make the first one?

Update

As requested, here is the (only) function that I need to call from managed code:

int new_game(double* params1, double* params2); 

One more question (although more complicated)

I have one view function

 int my_hard_to_interop_function(double** input, double **output, int width); 

where the input and output are two-dimensional double arrays. Their width is determined by the expression width , and their height is known by function. I have to call this method C from my C # application.

+4
source share
3 answers

If this is a simple C API, then the most direct way to access it is to use PInvoke. PInvoke was designed specifically for this scenario.

Could you post the signature of the C methods? If so, we could provide appropriate managed signatures.

EDIT

 [DllImport("insert_the_dll_name_here")] public static extern int new_game(ref double param1, ref double param2); 

As Hans pointed out, given the plural name of the parameters, it seems possible these are arrays versus single values. If so, then the signature will need to be changed to account for this. For example, if they are expected to be given fixed sizes, the signature will look like this:

 [DllImportAttribute("insert_the_dll_name_here"] public static extern int M1( [MarshalAsAttribute(UnmanagedType.LPArray, ArraySubType=UnmanagedType.R8, SizeConst=5)] double[] params1), [MarshalAsAttribute(UnmanagedType.LPArray, ArraySubType=UnmanagedType.R8, SizeConst=5)] double[] params2) ; 
+3
source

According to JaredPar, this is the easiest way to do this - and a really developed way to do it.

In particular, you will need your option 2, and the DLL should be available (along the way) from your executable.

+1
source

Since you need to deploy the C function in a separate DLL from your main C # program, using C ++ / CLI is the easiest anyway.

Do you have source code for C functions? If so, you can easily convert them to static member functions of the ref class . Then you can use the /clr:safe option and have clean managed code.

If you don’t have source code or your own code cannot work with ease of management (for example, it uses many functions of the C runtime library), then you can create a wrapper or facade, as you called it. The managed shell and native C code will be merged into a DLL, which will simplify deployment, since the DLL-based search path is not involved.

+1
source

All Articles