c# - 语言不支持
问题描述
我经常用 C++ 编写代码,对于我现在正在处理的特定项目,我正在编写一个 C++ 库,其方法将在 C# 库中使用,其方法将在 C# 应用程序中使用。
我在 Windows 10 上使用 Microsoft Visual Studio 2017。
我创建了一个包含 3 个项目的解决方案:
- 一个 C++/CLI 动态库 (
New Project => Visual C++ => CLR => Class Library
) - AC# 库 (
New Project => Windows Classic Desktop => Class Library (.NET Framework)
) - 还有一个 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++/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;
}
}
其余的保持不变。
推荐阅读
- reactjs - 如何在使用 axios 进行 CORS POST 后重定向
- python - python scipy.integrate quad 和 trapz 给出了两个不同的结果
- amazon-web-services - 更新到最新的 Amazon linux 但仍不推荐使用
- c# - 获取 DateTime 变量之间的时间(以小时为单位),但每个日期不超过 20 小时
- firebase - Firebase 实时数据库:为什么在未激活的情况下使用 Cloud Storage?
- java - 更改原生 Admob 样式
- javascript - 在包含对象的数组中使用扩展运算符是否被认为是在 redux reducer 中不可变地更新状态的好方法。?
- python - 使用余弦相似度法比较python中pandas数据框多列的文本
- php - 我无法正确配置 PHPMailer
- sql - 将无界数组的列添加到 SQL DB 表