首页 > 解决方案 > 语言不支持

问题描述

我经常用 C++ 编写代码,对于我现在正在处理的特定项目,我正在编写一个 C++ 库,其方法将在 C# 库中使用,其方法将在 C# 应用程序中使用。

我在 Windows 10 上使用 Microsoft Visual Studio 2017。

我创建了一个包含 3 个项目的解决方案:

  1. 一个 C++/CLI 动态库 ( New Project => Visual C++ => CLR => Class Library)
  2. AC# 库 ( New Project => Windows Classic Desktop => Class Library (.NET Framework))
  3. 还有一个 C# 应用程序 ( New Project => Windows Classic Desktop => Console App (.NET Framework))

现在,我只是想让这 3 个项目一起通信,我似乎在 C++ lib 和 C# lib 之间存在问题。

我的 C++ 库中的代码如下;

cppLib.h

#pragma once
#include <string>

using std::string;

using namespace System;

namespace cppLib {
    public ref class cppClass
    {
    public:
        static string test();
        static double add(double arg1, double arg2);
    };
}

cppLib.cpp

#include "cppLib.h"

namespace cppLib {
    string cppClass::test() {
        return "Hello World from C++ lib.";
    }

    double cppClass::add(double arg1, double arg2) {
        return arg1 + arg2;
    }
}

我的 C# lib 中的代码如下:

包装器.cs

using cppLib;

namespace CsWrapper
{
    public class Wrapper
    {
        //static public string TestCppLib()
        //{
        //    return cppClass.test();
        //}

        static public double Add(double arg1, double arg2)
        {
            return cppClass.add(arg1, arg2);
        }

        public string WrapperTest()
        {
            return "Hello World from C# lib.";
        }
    }
}

照原样,此代码构建时没有错误或警告。所以我可以static double add(double arg1, double arg2);在我的 C# lib 方法中从我的 C++ lib调用我的方法static public double Add(double arg1, double arg2),但是如果我尝试在Wrapper.cs中取消注释以下代码:

        //static public string TestCppLib()
        //{
        //    return cppClass.test();
        //}

我收到'cppClass.test(?)' is not supported by the language错误消息:

Severity    Code        Description                                             Project     File                                        Suppression State
Error       CS0570      'cppClass.test(?)' is not supported by the language     CsWrapper   D:\documents\...\CsWrapper\Wrapper.cs       Active

这是什么意思?如何在我的 C# 库中调用我的 C++ 库中的一种方法而没有问题,但另一种我不能?我的public string WrapperTest()方法返回一个字符串,我可以在我的 C# 应用程序中使用它(它可以工作,我可以显示它),那么为什么我不能在我的 C# 库中调用那个特定的 C++ 方法呢?这也是我第一次用 C# 编码。

标签: c#c++clr

解决方案


在 C++/CLI 中,如果 C# 应用程序/库要使用该方法,则不能将字符串作为本机 C++ 模板类型返回,因为 C# 代码不知道如何使用它。

必须使用该类型的托管(.Net 变体);对于 C++ string,它是一个String^. ^表示它是一个 ref 类(托管)指针。

代码变为:

cppLib.h

#pragma once
#include <string>

using std::string;

using namespace System;

namespace cppLib {
    public ref class cppClass
    {
    public:
        static String^ test();
        static double add(double arg1, double arg2);
    };
}

cppLib.cpp

#include "cppLib.h"

namespace cppLib {
    String^ cppClass::test() {
        return "Hello World from C++ lib.";
    }

    double cppClass::add(double arg1, double arg2) {
        return arg1 + arg2;
    }
}

其余的保持不变。


推荐阅读