【问题标题】:C# using my own C++/CLI DLL: Error: 'mytrainOp' is not supported by the languageC# 使用我自己的 C++/CLI DLL:错误:该语言不支持“mytrainOp”
【发布时间】:2016-09-22 15:48:05
【问题描述】:

我的 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
指针和固定大小的缓冲区只能在不安全的上下文中使用

专家,请帮忙。

【问题讨论】:

  • ref调用它,即obj.mytrainOp(ref i);
  • 另外,您不能只从 C# 中读取 std::string,您必须返回 System::String^,因此请返回 msclr::interop::marshal_as&lt;System::String^&gt;(ptr-&gt;train())(需要 #include &lt;msclr/marshal_cppstd.h&gt;) - 请参阅 @987654321 @.
  • 谢谢你,dbc abd Lucas

标签: c# c++ c++-cli mixed-mode


【解决方案1】:

这不是一个很好的错误消息,C# 编译器在试图弄清楚如何处理您返回的 std::string 对象时会遇到很大的困难。也很好地隐藏在您的 C# 程序中,因为您实际上并没有使用它。没关系,编译器还是需要处理的。

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

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

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

【讨论】:

  • 请帮助解决耦合问题.. [链接] (stackoverflow.com/questions/37458544/…)
  • 您正在转换为错误的类型。您需要转换为本机函数指针类型,而不是托管委托类型。通过为本机函数指针类型编写typedef 跌入成功坑。请关闭您的问题。
  • @Hans Passant:我真的没看懂你。我需要在 c# 中创建一个委托,将它传递给 c++/cli 函数,这没关系。现在我需要再次将此委托作为函数指针作为参数传递给本机类函数。现在你能帮忙吗?
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2022-06-13
  • 2011-07-31
  • 1970-01-01
  • 2011-02-25
  • 2022-12-04
  • 1970-01-01
相关资源
最近更新 更多