0

我需要从返回字符串的 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
    }
}

在返回之前,我是否必须对字符串进行某种编组魔法?

4

2 回答 2

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 放在一个类中。

于 2012-10-26T16:12:40.727 回答
0

我在这个十年前的页面上找到了答案。

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# 端将其编组为字符串。

于 2012-10-26T13:42:38.277 回答