我想将 C# 类的对象传递给 C++,并且在 native C++ 代码中想调用传递的对象上的某些方法。
Public class MyClass{
{
bool IsThisValid()
{
IsValid(this);//Check the Native passing it this object
}
[DllImport("mylibraryinCpp.dll", EntryPoint="IsValid", CharSet=CharSet.Unicode, CallingConvention=CallingConvention.StdCall) ]
static internal extern bool IsValid(object);
}//end of class
现在想要 C++ 代码获取此对象并对其执行一些操作。 在 native C++ 代码中,我的签名为
//Native C++ code mylibraryinCpp.dll
extern "C" __declspec(dllexport) BOOL __stdcall IsValid (VARIANT theObject)
{
((mscorlib::_object*)(thObject.pdispVal))->get_ToString(bstrStringVal);//AccessViolationException occurs here.
}
上面的代码大部分时间都在工作,但有时它会给出 AccessViolationException ,其他内存可能已损坏消息。 我对此很陌生,所以不确定这是将对象从 C# 传递到 C++ 的正确方法吗? 感谢您的任何建议
最佳答案
对象可能会被垃圾收集器移动。通常,您只需将函数指针传递给 native 代码——它可以由 JIT 从 .NET 中的委托(delegate)生成——这绝对有效。这称为反向 P/调用。
关于c# - 将纯 C# 对象传递给 C++ 并对该对象调用方法,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/6807432/