• 首页 首页 icon
  • 工具库 工具库 icon
    • IP查询 IP查询 icon
  • 内容库 内容库 icon
    • 快讯库 快讯库 icon
    • 精品库 精品库 icon
    • 问答库 问答库 icon
  • 更多 更多 icon
    • 服务条款 服务条款 icon

从托管代码调用C代码

用户头像
it1352
帮助1

问题说明

目前,我有,我想在.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.

正确答案

#1

如果这是一个简单的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) ;

这篇好文章是转载于:学新通技术网

  • 版权申明: 本站部分内容来自互联网,仅供学习及演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,请提供相关证据及您的身份证明,我们将在收到邮件后48小时内删除。
  • 本站站名: 学新通技术网
  • 本文地址: /reply/detail/tanhcgekhh
系列文章
更多 icon
同类精品
更多 icon
继续加载