1

My C++ class has only one method:

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();
}

It works fine.

C++/CLI class Library for this also has only one method:

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

It builds fine.

C# code consuming this DLL:

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 */
        }
    }
}

Intellisense Errors for the above line: Error 1 No overload for method 'mytrainOp' takes 1 arguments Error 2
Pointers and fixed size buffers may only be used in an unsafe context

Experts, Please help.

1 Answers1

2

It is not a great error message, the C# compiler struggles mightily when trying to figure out what to do with the std::string object you return. Also well hidden in your C# program since you don't actually use it. That doesn't matter, the compiler still needs to deal with it.

You must return a managed string instead, like this:

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

And of course if you don't actually have a use for that string then just declare the return value type as void. Next error you get is the one that reminds you to pass the argument with ref, you can figure that one out.

Hans Passant
  • 922,412
  • 146
  • 1,693
  • 2,536
  • Please help on coupled question.. [link] (http://stackoverflow.com/questions/37458544/c-cli-to-c-error-s-incompatible-with-void-stdcall-int-i-stdstring) – user5579704 May 26 '16 at 10:46
  • You are casting to the wrong type. You need to cast to the native function pointer type, not the managed delegate type. Fall in the pit of success by writing a `typedef` for the native function pointer type. Please close your question. – Hans Passant May 26 '16 at 10:57
  • @ Hans Passant: I really did not get you. I need to create a delegate in c#, pass it it c++/cli function which is ok. Now I need to again pass this delegate as a function pointer as a parameter to native class function. Now can you help? – user5579704 May 27 '16 at 08:12