简体   繁体   中英

passing string from C++/CLI class library to C#

I wrote a class library in VS 2010 C++/CLI and created a dll.

// testclass.h
#pragma once

#include <string>

namespace test
{
    public ref class testclass
    {
      public:
         std::string getstringfromcpp()
         {
            return "Hello World";   
         }
    };
}

And I want to use it in C# program, add this dll to reference then:

using test;
... 
testclass obj = new testclass();
textbox1.text = obj.getstringfromcpp();
...

What should I do with this issue?

For an interop scenario, you need to return a string object you'll be able to read from .NET code.

Don't return a std::string (there is no such thing in C#) or a const char * (readable from C# but you'd have to manage memory deallocation) or things like that. Return a System::String^ instead. This is the standard string type in .NET code.

This will work:

public: System::String^ getStringFromCpp()
{
    return "Hello World";   
}

But if you actually have a const char * or std::string object you'll have to use the marshal_as template:

#include <msclr/marshal.h>
public: System::String^ getStringFromCpp()
{
    const char *str = "Hello World";
    return msclr::interop::marshal_as<System::String^>(str);
}

Read Overview of Marshaling in C++ for more details.


To convert a System::String^ to std::string you can also use the marshal_as template, as explained in the above link. You just need to include a different header:

#include <msclr/marshal_cppstd.h>
System::String^ cliStr = "Hello, World!";
std::string stdStr = msclr::interop::marshal_as<std::string>(cliStr);

In my program somehow it refuses to convert the std::string directly to System::String^ but takes the char* casting ==> std::string.c_str()

public: System::String^ getStringFromCpp()
{
    std::string str = "Hello World";
    return msclr::interop::marshal_as<System::String^>(str.c_str());
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM