从托管代码中调用C代码 [英] Calling C code from managed code

查看:155
本文介绍了从托管代码中调用C代码的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

目前,我有,我想在.NET(C#)使用C函数

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

我可以看到实现这一目标的方式有两种:

I can see two ways of achieving this:


  1. 与VC ++。NET,/ CLR编译它(我认为这是可能的)已经实现了调用C立面管理方法代码。

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

编译C代码为DLL,然后进行API调用。

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

你怎么找到最好?如何做的第一人?

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

按照要求,这里是(只)函数I需要从我的托管代码中调用:

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



在这里输入和输出都是二维数组两倍。其宽度由宽度给予他们高度的功能闻名。我应该叫从我的C#应用​​程序本C方法。

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.

推荐答案

如果这是一个简单的C API那么最直接的的方式来访问它使用的PInvoke。 PInvoke的设计正是这种情形。

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.

您可以张贴中C方法的签名?如果这样我们就可以提供相应的管理特征。

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

修改

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

这篇关于从托管代码中调用C代码的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆