【发布时间】:2016-09-24 07:43:02
【问题描述】:
我是 C++/cli 新手,所以请原谅我提出愚蠢的问题或核心错误:
我的 C# 调用的 C++/CLI 类库只有一个方法:
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;
}
从 c++/cli 类调用的 C++ 类是:
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();
}
它编译得很好。
包装类 ERRORLINE 中的 Intellisense 错误: “myUpdateProgress”类型的 1 个参数与 ThreadsCppWrapper.cpp 中“void (__stdcall *)(int i, std::string str)”类型的参数不兼容
专家,请帮忙。
【问题讨论】:
-
你在哪里定义了
myUpdateProgress这个类型? (对于类型和变量/参数使用相同的名称非常令人困惑。) -
嗨,@molbdnilo,感谢您的回复。你能帮我写一下代码 sn-p 吗?
-
当智能感知和编译器不一致时,编译器是正确的。通常最好将 Intellisense 错误视为可能有用的提示。
-
@molbdnilo,我明白了。我的问题是如何将委托^从 c++/cli 传递给 c++ .....代码会有所帮助,因为我是新手。
-
如果代码按照你说的编译好,问题出在哪里?
标签: c++ c++-cli mixed-mode