1
votes

I am trying to make an interface with another program so I have to use C++.

It's been years since I have programmed in C++ and I have been at this problem for about a week so I'm slowly starting to see how everything works.

I want to read byte data coming from a serial port device.

I have verified that I can get text through the serial port using the readline command:

For example:

String^ message = _serialPort->Readline();

Is how the data is read in an example from MSDN that I got to work successfully.

However I have tried to modify it several times and I'm having no luck coming up with something that reads the data as bytes. (I already have conversion of byte data to string so I can actually see the bytes such as the number 15 equaling 0f in bytes.)

Modifying the code to

wchar_t message = _serialPort->Readline();

gives me

error c2440: 'initializing' : cannot convert from System::String ^' to 'wchar_t'.

I'm not familiar with Readline. Is it only for strings? I have verified that it does work with strings and if I use a serial device that sends a string the first set of code does work.

Can someone explain what method I could use to read byte data? Thanks.

2
How is _serialPort defined? Why are trying to convert output to wchar_t when you want bytes? What is System::String^ ?ravenspoint
Without diving to the depths of the mechanism, Readline() returns a line, not a character, so assigning it to a character won't work. Secondly, it clearly returns a System::String ^ so you should probably be using that instead.Assaf Levy
I see from sehe's answer that this is not C++. Please fix question title and tags.ravenspoint

2 Answers

1
votes

If you actually want to use C++ rather than C++/CLI, I recommend using boost.asio. It is well established, relatively easy to understand, and has a specific set of functionality just for working with serial ports.

1
votes

Update

Pure C++ Win32 API versions:

See the following good references

Is there any specific reason you are doing this in C++/CLI code?

I thought you might not even be aware of that (otherwise, tag your questions, please).

String^, Readline etc are CLR functions (i.e. .NET, think: "you could do this more easily in C#). So, again,

  • If there is a need for this to be in C++, why don't you look at the native Win32 API
  • Otherwise, why are you bothering with C++

If you really wanted C++/CLI I suggest not mixing native/managed code when handling the serial IO. You can get an UnmanagedMemoryStream to marshal the data in/out of managed land.

$0.02