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
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.