passing _bstr_t between c# and C++ /CLI

561 Views Asked by At

I am little confused whether we can use _bstr_t to pass string between c# to C++ and vice versa.

I am using C++/CLI as intermediate layer between C# and C++.

If possible also give example how to marshal it at C# end and C++/CLI end as there are not much documentation around that

Also suggest better data type/ mechanism to pass string.

1

There are 1 best solutions below

2
On

According to MSDN, this should work for converting String^ to string (and it's the easiest way by far). However I cannot test, my VC++2008 Express doesn't find Marshal.h...

// TestCppCli2008.cpp : main project file.

#include "stdafx.h"
#include <string>
#include <msclr\marshal.h>
#include <msclr\marshal_cppstd.h>

using namespace System;
using namespace msclr::interop;

int main()
{
    System::String^ s = L"Hello World";

    std::string str = marshal_as<std::string>(s);
    return 0;
}