Passing a string from C ++ to C #

I am using PInvoke, the inverse of PInvoke, as described by Thottam R. Sriram http://blogs.msdn.com/b/thottams/archive/2007/06/02/pinvoke-reverse-pinvoke-and-stdcall-cdecl.aspx

Everything seems to work fine, except for passing a string from C ++ to C.

(In Sriram, a string is built in C # and passed intact through C ++, so the problem can be avoided.)

C # code is as follows

class Program
{
    public delegate void callback(string str);
    public static void callee(string str)
    {
        System.Console.WriteLine("Managed: " + str);
    }

    static void Main(string[] args)
    {
        gpscom_start(new callback(Program.callee));

        Console.WriteLine("NMEA COM Monitor is running");
        System.Threading.Thread.Sleep(50000);
    }

    [DllImport("gpscomdll.dll", CallingConvention = CallingConvention.StdCall)]
    public static extern void gpscom_start(callback call);

}

C ++ code is as follows:

extern "C" dllapi void __stdcall gpscom_start(void (__stdcall *callback) (BSTR str))
{

BSTR bstr = SysAllocString(L"starting monitor");
(*callback)(bstr);
SysFreeString(bstr);

Everything looks good on startup except for the callback line

Managed: m

It looks like the UNICODE string is printed using the ANSI procedure, but certainly the C # lines are unicode?

TIA

+3
source share
2 answers

P/Invoke MarshalAs . , [MarshalAs(UnmanagedType.BStr)] .

public delegate void callback([MarshalAs(UnmanagedType.BStr)]string str);

, - BSTR , IntPtr . Marshal.PtrToStringBSTR .

+4

# - UTF-16. , # LPWSTR - , BSTR. , wchar_t *, BSTR.

+1

Source: https://habr.com/ru/post/1780535/


All Articles