在C#项目中引用C ++ / CLI类库(已编译的dll)

时间:2014-12-31 00:32:10

标签: c# dll reference c++-cli

我有一个非常简单的C ++类库,其中包含两种帐户类型:正在检查节省。我已经构建了这个项目并将其编译成一个名为Accounts的.dll。我在C#Console应用程序中引用了 Accounts.dll 。无济于事,我试图分别从储蓄检查类中使用静态类存款撤销 。我没有看到函数显示在对象浏览器或智能感知中,当我尝试访问这些函数时,我无法构建它,否则当我注释掉对mySavings.deposit的调用时,我能够构建并运行它。 (ARG1,ARG2)...

知道我在这里做错了什么吗?我经常从其他项目和第三方引用.dll,但这是第一次在C#项目中引用C ++ .dll。

C ++类库

#pragma once
using namespace System;

namespace Accounts {

  public ref class Savings
  {
    public:
        unsigned accountNumber;
        double balance;
        static double deposit(Savings s, double amount)
        {
            s.balance += amount;
            return s.balance;
        }
  };

  public ref class Checking
  {
    public:
        unsigned accountNumber;
        double balance;
        static double withdraw(Checking c, double amount)
        {
            c.balance -= amount;
            return c.balance;
        }
  };
}

引用上述编译动态链接库的C#控制台应用程序

using Accounts;

class Program
{
  static void Main(string[] args)
  {
    Savings mySavings = new Savings();  // works but object is empty
    mySavings.deposit(mySavings, 100);  // still breaks
  }
}

我收到以下错误:'Accounts.Savings'不包含'deposit'的定义,并且没有扩展方法'deposit'接受类型'Accounts.Savings'的第一个参数可以找到(你错过了吗?使用指令或程序集引用?)

非常感谢任何帮助。

1 个答案:

答案 0 :(得分:2)

你认为C#可以访问C ++类......它不能。但是C ++ / CLI可以创建C#可以使用的.NET类型。但是,这些遵循.NET的规则,有时与C ++不同。

首先,您必须在C ++ / CLI代码中使用ref class(或ref structvalue classvalue struct):

public ref class Savings

然后,您需要初始化C#引用以指向对象。简单地在C#中声明变量不足以构造对象默认构造(不是对于引用类型,变量将是null或未初始化,而不是对于值类型,其中内容将全为零或未初始化,没有调用构造函数。)

Savings mySavings = new Savings();

之后,你会发现除了通过跟踪句柄之外,C ++ / CLI不能引用.NET引用类型......所以不是

Savings&

你需要

Savings% // tracking reference, but C# doesn't know what to do
         // with a function whose parameter is like this

Savings^ // tracking pointer, C# likes it fine, C++/CLI will need -> to access members

最后,从C#调用静态函数的语法是

Savings.deposit(mySavings, 100);
// ^^ class name, not object

但是,无论如何,这可能应该是非静态成员,对吗?

相关问题