我需要从c#调用一个返回String的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
}
}
在返回之前,我是否必须使用字符串进行某种编组魔术?
答案 0 :(得分:1)
为什么你首先使用函数指针?只需将委托的实例传递给C#代码:
<强> C ++:强>
static String^ CppFunctionThatReturnsString()
{
return gcnew String("From C++");
}
void main()
{
CSharp::CSharpFunction(new CSharp::CppFuncDelegate(CppFuncThatReturnsString));
}
<强> C#:强>
public class CSharp
{
private delegate string CppFuncDelegate();
public static void CSharpFunction(CppFuncDelegate d)
{
d();
}
}
我认为你可能需要将CppFuncThatReturnsString放在一个类中。
答案 1 :(得分:0)
我在this ten year old page找到了答案。
C ++:
static const char* __stdcall CppFunctionThatReturnsString()
{
return "From C++";
}
void main()
{
CSharp::CSharpFunction(IntPtr(CppFunctionThatReturnsString));
}
C#:
public class CSharp
{
private delegate IntPtr CppFuncDelegate();
public static void CSharpFunction(IntPtr cppFunc)
{
var func = (CppFuncDelegate)Marshal.GetDelegateForFunctionPointer(cppFunc, typeof(CppFuncDelegate));
Marshal.PtrToStringAnsi(func());
}
}
也就是说,将其作为IntPtr传递并将其编组为C#端的字符串。