Home > Backend Development > C++ > How to Efficiently Convert Between System::String and std::string in C .NET?

How to Efficiently Convert Between System::String and std::string in C .NET?

Susan Sarandon
Release: 2024-10-30 21:12:03
Original
750 people have browsed it

How to Efficiently Convert Between System::String and std::string in C   .NET?

Using the Marshal Class to Convert between System::String and std::string

Translating between System::String in C .NET and std::string in C can be a common task. The marshal_context class provided by MS provides a clean and efficient way to achieve this.

Syntax:

<code class="CPP">msclr::interop::marshal_context context;
std::string standardString = context.marshal_as<std::string>(managedString);</code>
Copy after login

Example:

<code class="CPP">#include "stdafx.h"
#include <string>

#include <msclr/marshal_cppstd.h>

using namespace System;

int main(array<System::String ^> ^args)
{
    System::String^ managedString = "test";

    msclr::interop::marshal_context context;
    std::string standardString = context.marshal_as<std::string>(managedString);

    return 0;
}</code>
Copy after login

Benefits:

  • The marshal_context class provides additional safety and exception handling compared to manual memory management.
  • The syntax is concise and easy to read.

Alternative Conversions

The MSDN article referenced by the answer also provides other conversion methods, such as:

  • Using COM interop marshalling functions like SysStringToBSTR.
  • Using the MarshalAs attribute with platform invoke functions.

The above is the detailed content of How to Efficiently Convert Between System::String and std::string in C .NET?. For more information, please follow other related articles on the PHP Chinese website!

source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Latest Articles by Author
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template