问题描述
您好,
我正在编写一个C ++应用程序来向串口发送数据。当我尝试创建一个包含所有命令的文件并将其链接到我的主文件时,我的问题出现了。我需要访问我的主要表单Communicate.h中定义的serialport1对象(我将范围从私有更改为公共):
Hi there,
I am writing a C++ application to send data down a serial port. My problem arises when I attempt to create a file with all my commands in and link that to my main file. I need to access the serialport1 object defined here in my main form "Communicate.h" (I changed the scope from private to public):
public: System::IO::Ports::SerialPort^ serialPort1;
我需要在Commands.cpp中访问它我试试这样:
I need to access this in Commands.cpp I try it like this:
#include "Commands.h"
#include "Communicate.h"
using namespace SerialCommunications;
using namespace System;
using namespace System::IO::Ports;
void elbow(int dir, int amt)
{
array<Byte>^ cmd = { 0xff, 0xff, 0xff };
Communicate::serialPort1->Write(cmd, 0, 3);
}
但是我刚收到此错误信息试图访问它:
错误:非静态成员引用必须与特定对象相关
提前致谢!!
Max
However I just get this error message trying to access it:
"Error: a nonstatic member reference must be relative to a specific object"
Thanks in advance!!
Max
推荐答案
// Create a new SerialPort object with default settings.
serialPort1 = gcnew System::IO::Ports::SerialPort();
请参考此处的示例:
[]
也许将声明移到类中并将其实例化构造函数。
没有你的代码我不知道。首先也是最重要的是我会问你为什么使用C ++ / clr而不是C#。
这是一个简单的例子,它只是向你展示机制。
communic.h
Refer to the example here:
https://msdn.microsoft.com/en-us/library/system.io.ports.serialport(v=vs.110).aspx?cs-save-lang=1&cs-lang=cpp#code-snippet-1[^]
Maybe move the declaration to the class and instantiate it in the constructor.
Without your code I have no idea. First and most importantly I would ask why you are using C++/clr and not C#.
Here is a simple example JUST to show you the mechanism.
communicate.h
using <System.dll>
using namespace System;
using namespace System::IO::Ports;
namespace SerialCommunications
{
ref class communicate
{
public:
communicate(void)
{
// Create a new SerialPort object with default settings.
serialPort1 = gcnew SerialPort();
};
private:
SerialPort^ serialPort1;
public:
void Write(array<unsigned char> ^ buffer, int offset, int count)
{
serialPort1->Write(buffer, offset, count);
}
};
}
然后
then
/ testclr.cpp : main project file.
#include "stdafx.h"
#include "communicate.h"
using namespace System;
using namespace SerialCommunications;
int main(array<System::String ^> ^args)
{
communicate^ myCommunicate = gcnew communicate();
array<Byte>^ cmd = gcnew array<Byte>{ 0xff, 0xff, 0xff };
myCommunicate->Write(cmd, 0, 3);
return 0;
}
public: System::IO::Ports::SerialPort^ serialPort1;
to:
to:
public: static System::IO::Ports::SerialPort^ serialPort1;
非常感谢,
Max
Thank you very much,
Max
这篇关于在C ++文件中使用串口对象的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!