Calling C code from managed code

廉价感情. 提交于 2019-12-06 05:45:49

问题


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

I can see two ways of achieving this:

  1. Compiling it (I think this is possible) with /clr on VC++.NET, having implemented "façade" managed methods that call the C code.

  2. Compiling the C code as a DLL and then making API calls.

What do you find best? How to do the first of them?

Update

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

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

Just one more question (though harder)

I have one function of the form

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

where input and output are both 2D double arrays. Their width is given by width and their height is known by the function. I am supposed to call this C method from my C# application.


回答1:


If this is a simple C API then the most straight forward way to access it is using PInvoke. PInvoke was designed for exactly this scenario.

Could you post the signature of the C methods? If so we could provide the 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 vs. single values. If so then the signature would need to change to account for that. For example if they are expected to be a predetermined fixed size the signature would look like the following

[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) ;



回答2:


As JaredPar states, this is the easiest way to do it - and indeed the designed way to do it.

Specifically, you'll need your option 2 and the .dll will need to be accessible (path wise) from your executable.




回答3:


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

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

If you don't have source code, or the native code can't run as managed easily (uses lots of C runtime library functions, for instance), then you can build a wrapper or façade as you called it. The managed wrapper and native C code will end up together in the DLL which makes deployment easier, since the native DLL search path isn't involved.



来源:https://stackoverflow.com/questions/4002240/calling-c-code-from-managed-code

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!