我需要从返回字符串的 c# 调用 c++ 回调函数。当我尝试使用下面的代码时,应用程序会严重崩溃(一条消息说这可能是由于堆损坏造成的)。
这是C++代码:
static String^ CppFunctionThatReturnsString()
{
return gcnew String("From C++");
}
void main()
{
CSharp::CSharpFunction(IntPtr(CppFunctionThatReturnsString));
}
这是c#代码:
public class CSharp
{
private delegate string CppFuncDelegate();
public static void CSharpFunction(IntPtr cppFunc)
{
var func = (CppFuncDelegate)Marshal.GetDelegateForFunctionPointer(cppFunc, typeof(CppFuncDelegate));
func(); // Crash
}
}
在返回之前,我是否必须对字符串进行某种编组魔法?