【发布时间】:2012-10-26 12:09:22
【问题描述】:
我需要从 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
}
}
在返回之前我是否必须对字符串进行某种编组魔术?
【问题讨论】:
标签: c++-cli marshalling function-pointers managed managed-c++