Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

c++

c#

types

I wave a method in C++ that receives a parameter of the LPCOLESTR type. I'm accessing this method through C#, but I can't make the correct conversion between String and this type.

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

void Something(LPCOLESTR str)

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

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

But with no luck, of course. If anyone can help me, I'd be very glad. Thank you!


Code snippet:

As an example, here's my C++ portion of code, defined in the file MixedCodeCpp.h (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's my code in C# (I've added a reference 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);
like image 294
Luís Mendes Avatar asked Feb 07 '26 15:02

Luís Mendes


1 Answers

The argument will appear as Char* on the C# side. That requires unsafe code, like this:

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

It makes very little sense to expose the LPCOLESTR to other managed code. This method really should accept a String^ and convert to wchar_t* internally.

like image 140
Hans Passant Avatar answered Feb 09 '26 06:02

Hans Passant



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!