0

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.

user2692032
  • 771
  • 7
  • 26
  • Between C# and C++/CLI, you can just use `System::String^`. As for between C++/CLI and native C++, well... what does your native C++ code need? – Medinoc Aug 26 '13 at 08:00
  • I need to pass string in some way to native C++, So how shall i marshal System::String^. Shall i go for char * in native C++ or some other data type? I also need to pass value back to C# from native C++. How shall i do tht? – user2692032 Aug 26 '13 at 11:07
  • You mean native C++ needs std::string? – Medinoc Aug 26 '13 at 20:19
  • It depends on your C++ code and libraries. Which string data structure, character set and encoding would work best? How will the data structure be allocated and freed? If the character set is not what C# uses (Unicode), how do you want to handle a mismatch in each direction? – Tom Blodget Aug 28 '13 at 03:18

1 Answers1

0

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;
}
Medinoc
  • 6,577
  • 20
  • 42
  • There used to be a website marshal-as dot net where you could download the `marshal_as` template stuff, including overloads to support new data types, which was a way to get it on Express Edition. Unfortunately it looks like the registration expired and the domain has been co-opted for advertisements... – Ben Voigt Aug 27 '13 at 16:00
  • 1
    BTW, that file should be included in VC++ 2010 Express, just not 2008. – Ben Voigt Aug 27 '13 at 16:07