简体   繁体   中英

Use C++ class in C# with strings (Dll)

I am trying to use my C++ class in my C# program. So I made a .dll-file to use it in C#. My problem is, that I am working with strings. My question is: How can I return a std::string to my C# program?

My C++ class (header-file):

using namespace std;

class CComPort
{
public:     
    string ReadLine();          
    void WriteLine(string userInput);
};

My dll code:

string CppWrapper::CComPortWrapper::ReadLineWrapper()
{
    return comPort->ReadLine();
}

void CppWrapper::CComPortWrapper::WriteLineWrapper(string userInput)
{
    comPort->WriteLine(userInput);
}

My C#-Code:

comPort.WriteLineWrapper(tb_send.Text);

Error:

'CComPortWrapper.WriteLineWrapper(?,?)' is not supported by the language.

I tried to change the dll file to something like this, but it didn't worked:

void CppWrapper::CComPortWrapper::WriteLineWrapper(String ^ userInput)
{
    comPort->WriteLine(userInput);
}

What is the rigth way to change it?

It appears that you're wrapping a class used just for serial port communication. There are ways of accessing the serial port directly from C#, without needing C++/CLI. Unless there's a lot of logic in the C++ class that cannot be ported/would be hard to port to C#, please do consider doing the serial communication in C#.


You haven't shown us the declaration of your CComPortWrapper class. I'm assuming that it's public ref class CComPortWrapper .

If the goal of your wrapper is to make it callable from managed languages (eg, C#), then you should use managed types in your declaration.

In this case, you should declare the methods of CComPortWrapper to take & return System::String^ . Within the wrapper, convert it to/from std::string , and call the unmanaged class with that.

I recommend using marshal_as to do the conversion, especially since you're converting from one class to another. You don't need to deal with explicitly allocating memory or anything like that; let each string class manage its own memory, and let marshal_as deal with copying & converting the data.

#include <msclr\marshal_cppstd.h>

using namespace System;

String^ CppWrapper::CComPortWrapper::ReadLineWrapper()
{
    std::string result = comPort->ReadLine();
    return marshal_as<String^>(result);
}

void CppWrapper::CComPortWrapper::WriteLineWrapper(String^ userInput)
{
    std::string input = marshal_as<std::string>(userInput);
    comPort->WriteLine(input);
}

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