Convert managed strings (C #) to LPCOLESTR (C ++)

I am excited about a method in C ++ that gets a parameter of type LPCOLESTR. I am accessing this method through C #, but I cannot do the proper conversion between String and this type.

Let's say the signinature method in C ++:

void Something(LPCOLESTR str)

In C #, I'm trying to call it (all the reference problems for accessing the method through the DLL have already been solved):

String test = "Hello world";
Something(test);

But of course, no luck. If anyone can help me, I would be very happy. Thank!


Code snippet:

As an example, here is my part of the C ++ code defined in the MixedCodeCpp.h file (CLR Class Library)

#include "windows.h"  
#pragma once  
using namespace System;

namespace MixedCodeCpp
{
    public ref class MyClass
    {
    public:
        HRESULT Something(LPCOLESTR str)
        {
            return S_OK;
        }
    };
}

And here is my code in C # (I added a link to the C ++ project in the C # project through Visual Studio):

StringBuilder sb = new StringBuilder();  
sb.Append("Hello world");  
MixedCodeCpp.MyClass cls = new MixedCodeCpp.MyClass();  
cls.Something(sb);
+3
source share
2 answers

Char * #. , :

    unsafe static void CallSomething(MyClass obj, string arg) {
        IntPtr mem = Marshal.StringToCoTaskMemUni(arg);
        try {
            obj.Something((Char*)mem);
        }
        finally {
            Marshal.FreeCoTaskMem(mem);
        }
    }

LPCOLESTR . String ^ wchar_t * .

+1

StringBuilder String:

System.Text.StringBuilder test = new System.Text.StringBuilder ();
test.Append("Hello world");
Something(test);

pinvoke Win32, . , API, . MSDN . .

, . ( .)

[DllImport(SomeLib.SomeName, CharSet = CharSet.Unicode, SetLastError = true)]
[return: MarshalAs(UnmanagedType.Bool)]
public static extern bool Something(StringBuilder pMyString);

StringBuilder str = new StringBuilder(MAX_PATH); 
DWORD uSize;

bool b = Something(str);
0

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