使用我自己的 C++/CLI DLL 的 C#:错误:语言不支持'mytrainOp'

C# using my own C++/CLI DLL: Error: 'mytrainOp' is not supported by the language

本文关键字:mytrainOp 错误 不支持 语言 自己的 我自己 C++ DLL CLI      更新时间:2023-10-16

我的C++类只有一个方法:

string MyThreadsCpp::MyThreadsCppClass::train(){
    double sum = 0.0;
    long max = 100 * 1000;
    int perc = 0;;
    for (long n = 0; n < max; n++){
        sum += 4.0*pow(-1.0, n) / (2 * n + 1.0);
        int rem = n % (max/10);
        if (rem == 0){
            perc = 100 * n / max;
            cout << perc << "%" << endl;
        }
    }
    cout << "100%" << endl;
    ostringstream oss;
    oss << "Result = " << sum;
    return oss.str();
}

它工作正常。

为此C++/CLI 类库也只有一种方法:

string ThreadsCppWrapper::ThreadsCppWrapperClass::mytrainOp(int% i){
    i++;
        return ptr->train();
}

它构建良好。

使用此 DLL 的 C# 代码:

namespace ThreadsCsharp
{
    public partial class FrmMain : Form
    {
       private void btnTrain_Click(object sender, EventArgs e)
        {
            ThreadsCppWrapperClass obj = new ThreadsCppWrapperClass();
            int i = 5;
            obj.mytrainOp(i); /* This is where I get Error */
        }
    }
}

上述行的智能感知错误:错误 1 方法"mytrainOp"没有重载需要 1 个参数错误 2
指针和固定大小的缓冲区只能在不安全的上下文中使用

专家,请帮忙。

这不是一个很好的错误消息,C# 编译器在尝试弄清楚如何处理返回的std::string对象时非常挣扎。 也很好地隐藏在您的 C# 程序中,因为您实际上并不使用它。 没关系,编译器仍然需要处理它。

您必须返回一个托管字符串,如下所示:

String^ ThreadsCppWrapper::ThreadsCppWrapperClass::mytrainOp(int% i){
    i++;
    return gcnew String(ptr->train().c_cstr());
}

当然,如果您实际上没有使用该字符串,则只需将返回值类型声明为 void 。 你得到的下一个错误是提醒你用ref传递参数的错误,你可以弄清楚那个错误。