How to return text from Native (C++) code

前端 未结 5 1228
無奈伤痛
無奈伤痛 2020-11-27 14:50

I am using Pinvoke for Interoperability between Native(C++) code and Managed(C#) code. What i want to achieve is get some text from native code into my managed code. For thi

5条回答
  •  自闭症患者
    2020-11-27 15:25

    If you're returning a char *, and don't want to have to modify the C/C++ code to allocate memory for your return value (or you can't modify that code), then you can change your C# extern function-prototype to return an IntPtr, and do the marshaling yourself.

    For instance, here's a snippet of the interop I wrote for Pocketsphinx:

    [DllImport("sphinxbase.dll", CallingConvention = CallingConvention.Cdecl)]
    private static extern IntPtr /* char const * */ jsgf_grammar_name(IntPtr /* jsgf_t * */ jsgf);
    

    And here's the get-accessor for the C# JsgfGrammar class. m_pU is an IntPtr that points to the raw jsgf_t object.

    public string Name
    {
        get
        {
            IntPtr pU = jsgf_grammar_name(m_pU);
            if (pU == IntPtr.Zero)
                strName = null;
            else
                strName = Marshal.PtrToStringAnsi(pU);
            return strName;
        }
    }
    

    Modifying this example for other string formats (e.g. Unicode) should be trivial.

提交回复
热议问题