Get "this" reference into static pointer array

Go To Last Post
5 posts / 0 new
Author
Message
#1
  • 1
  • 2
  • 3
  • 4
  • 5
Total votes: 0

Hello guys,

I am a newbie so take me easy

I want to get "this" address and store it in a static array of class itself pointers.

In the header file I have:

class Usart
{
    public:
    void Init();
    ...
    ...
    private:
    static Usart *ptrUsart[USART_NUM];
    uint8_t usartNumber;
    ...
    ...

}

 

In the cpp file:

Usart *Usart::ptrUsart[] = {0, 0, 0, 0, 0};

Usart::Usart(uint8_t num)
{
    this->usartNumber=num;
}

void Usart::Init()
{
    Usart::ptrUsart[this->usartNumber] = this;
    ...
    ...
}

 

When I debug with Atmel studio 7 the ptrUsart array values remains always 0. Seem that the Usart::ptrUsart[this->usartNumber] = this;​ statement doesn't works.

If I try to do ​void *foo=this; seem to work correctly

Can you help me?

Thanks
 

  • 1
  • 2
  • 3
  • 4
  • 5
Total votes: 0

With CPP there is very little difference between a class and a structure.

The only diference is that members in a structure are by default public, and in a class the default is private.

You can simple take the address of a class just like of any other variable.

 

#include <stdio.h>	// My best cpp :)

class Usart {
public:
	int Number;
	void Init(void);

};

void Usart::Init( void) {
	printf( "%d\n", Number);
}

Usart SerialPort1;
Usart SerialPort2;
Usart SerialPort3;

Usart * Array[] = {&SerialPort1, &SerialPort2, &SerialPort3};

int main (void) {

	Array[0]->Number = 12;
	Array[1]->Number = 34;
	Array[2]->Number = 56;

	SerialPort2.Init();

	for( int Cnt=0; Cnt < sizeof Array/sizeof Array[0]; ++Cnt) {
		Array[Cnt]->Init( );
	}
}

Save the above as: asdf.cpp and then:

paul@dualcore:~$ make asdf
g++     asdf.cpp   -o asdf
paul@dualcore:~$ ./asdf
34
12
34
56

P.s:

"make" can do a lot of things without a makefile by using a bunch of default rules.

Make guesses that ".cpp" files should be compiled with a cpp compiler and lots of other stuff...

 

Doing magic with a USD 7 Logic Analyser: https://www.avrfreaks.net/comment/2421756#comment-2421756

Bunch of old projects with AVR's: http://www.hoevendesign.com

Last Edited: Sun. Apr 29, 2018 - 05:33 PM
  • 1
  • 2
  • 3
  • 4
  • 5
Total votes: 0

llisotti, the code you posted looks correct for me, so the issue is apparently in the part of the code you didn't post. Please post the complete code.

  • 1
  • 2
  • 3
  • 4
  • 5
Total votes: 0

Thank you guys for your replies.

I'm trying to make a generic Usart library in C++. For the scope i would like implement this solution: https://waterproofman.wordpress.com/2007/02/07/avr-interrupts-in-c/. The object have to be accessed from ISR routine through static array above. I tried loopback test  (TX -> RX) and seem the code works well !! Maybe it's an Atmel studio debug problem with static variables? I don't know

  • 1
  • 2
  • 3
  • 4
  • 5
Total votes: 0

Have you looked at how Arduino does this?