问题
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