C++/CLI : Why can't I pass Strings by reference?

10,194

Solution 1

Sounds like you are using Managed C++, which is a bastardised C++ used with the .NET Framework.

in Managed C++, I believe the syntax you are looking for is System::String^. The reason for this is that since managed types are garbage collected by .NET Framework, you aren't allowed to create 'regular' references since the GC needs to track all the references to a specific variable to know when it is safe to free it.

Solution 2

First of all, there are really two Microsoft-specific C++ dialects for .NET: the older "Managed C++" (Visual Studio 2002 and 2003) and C++/CLI (Visual Studio 2005 and later).

In C++/CLI, System::String^ is a .NET reference to a string; some authors call this a "tracking pointer" to compare and contrast it with a normal C++ pointer. As in C++, you can pass .NET references "by reference", but instead of using &, you use %, as in:

void makeStr(System::String^ %result) {
   result = gcnew System::String("abc");
}

Solution 3

It looks like you are using Managed C++. You should use System::String^ instead.

Share:
10,194

Related videos on Youtube

Casebash
Author by

Casebash

Bachelor of Science (Adv Maths) with Honors in Computer Science from University of Sydney Programming C/C++/Java/Python/Objective C/C#/Javascript/PHP

Updated on May 06, 2022

Comments

  • Casebash
    Casebash about 2 years

    Why doesn't Microsoft's C++/CLI allow me to pass strings by reference? I received the following error:

    C3699: '&': cannot use this indirection on type 'System::String'

    • configurator
      configurator over 13 years
      I added the C++-cli tag because it looks like that's what you're using here.
  • jwadsack
    jwadsack over 13 years
    Take a look at Microsoft's tutorial on Data Marshaling for an in-depth discussion on how memory is managed between native C/C++ and Managed C++. msdn.microsoft.com/en-us/library/ms384317(VS.71).aspx
  • user1606191
    user1606191 over 6 years
    Do we explicitly need to delete the variable "result" passed from C# layer or does the GC takes care of deleting it?
  • csjoseph
    csjoseph almost 3 years
    I think GC will take care of it.