使用C#调用c ++程序集

时间:2011-05-26 06:36:08

标签: c# c

我有一个c ++ dll,我需要在我的.NET代码中使用它。

如何调用此库中的方法,并在我的代码中使用结果?

e.g。 C ++库有一个名为Move(int)的方法,它返回1表示true,0表示false。

我没有编写C ++库,它用于控制机器人机器的移动。

2 个答案:

答案 0 :(得分:3)

您可以使用P/Invoke。因此,例如,如果您的非托管库导出一个函数,该函数将整数值作为参数并返回另一个整数,您可以在C#中使用[DllImport]属性为此方法定义托管包装:

[DllImport("foo.dll")]
public static extern int Move(int arg);

然后直接在托管代码中使用此方法:

int result = Move(123);

答案 1 :(得分:3)

http://msdn.microsoft.com/en-us/library/ms173184.aspx

using System.Runtime.InteropServices;
...
public class MyClass
{
    #region PInvokes
    [DllImport("Your.dll")]
    static public extern int Move(int val);
....

如果有一次,你需要使用Interop C ++类,这里有一篇很好的文章。 http://www.codeproject.com/KB/cs/marshalCPPclass.aspx

相关问题