C++/cli to c++: Error s incompatible with “void (__stdcall *)(int i, std::string str)”

妖精的绣舞 提交于 2019-12-25 17:03:40

问题


I am new to C++/cli so please excuse me for silly questions or core mistakes:

My C++/CLI class Library that is called by C# has only one method:

ThreadsCppWrapper.h

namespace namespace ThreadsCppWrapper {

public ref class ThreadsCppWrapperClass
    {
        public:
        ThreadsCppWrapperClass(); // Constructor

        System::String^ mytrainOp(System::MulticastDelegate^ callbackfunction);
    private:
        MyThreadsCpp::MyThreadsCppClass* ptr;
    };
}

ThreadsCppWrapper.cpp

System::String^ ThreadsCppWrapper::ThreadsCppWrapperClass::mytrainOp(System::MulticastDelegate^ callbackfunction){

System::String^ toReturn = gcnew System::String("");

msclr::interop::marshal_context context;
System::IntPtr intPtr = System::Runtime::InteropServices::Marshal::GetFunctionPointerForDelegate(callbackfunction);
if (intPtr != System::IntPtr::Zero)
{
    myUpdateProgress functPtr = static_cast<myUpdateProgress>(intPtr.ToPointer());
    string stdstringResult = ptr->train(functPtr); // Error Here   // ERRORLINE

    //toReturn = context.marshal_as<System::String^>(stdstringResult);
}
else
{
    System::Console::WriteLine("Error: Could not cast delegate!!");
}
return toReturn;
}

The C++ class that is called from c++/cli class is:

MyThreadsCpp.h

namespace MyThreadsCpp{

class MyThreadsCppClass
{
public:
    MyThreadsCppClass();
    string train(void(CALLBACK *myUpdateProgress)(int i, string str));
};

}

MyThreadsCpp.cpp

string MyThreadsCpp::MyThreadsCppClass::train(void(CALLBACK *myUpdateProgress)(int i, string str)){

double sum = 0.0;
long max = 100 * 1000;
int perc = 0;;
string trainstat = "Training Status: Starting Training...";
ostringstream oss;

    myUpdateProgress(perc, trainstat);
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;
        /* report completion status */
        oss << "Training Status: " << perc;
        myUpdateProgress(perc, oss.str());
    }
}
cout << "100%" << endl;
ostringstream oss;
oss << "Result = " << sum;
return oss.str();
}

It compiles fine.

Intellisense Error in wrapper class ERRORLINE: 1 argument of type "myUpdateProgress" is incompatible with parameter of type "void (__stdcall *)(int i, std::string str)" in ThreadsCppWrapper.cpp

Experts, Please help.


回答1:


You cannot use std::string and System::String^ interchangeably. You must convert them to one type. Forceful conversion of type or the function-pointer/callback won't work - it will break at runtime, if not compile time.



来源:https://stackoverflow.com/questions/37458544/c-cli-to-c-error-s-incompatible-with-void-stdcall-int-i-stdstring

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!