开发者

Reading Byte Data through the serial port in C++/CLI

开发者 https://www.devze.com 2023-02-26 05:42 出处:网络
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

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开发者_Python百科 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.


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.


Update

Pure C++ Win32 API versions:

See the following good references

  • CodeProject article
  • MSDN

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

0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号