从c#调用的c ++函数指针返回字符串

时间:2012-10-26 12:09:22

标签: c++-cli marshalling function-pointers managed managed-c++

我需要从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
    }
}

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

2 个答案:

答案 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#端的字符串。