?
Solved

Global variable of type BYTE

Posted on 2005-04-09
7
Medium Priority
?
542 Views
Last Modified: 2013-11-20
I need to define an array of type BYTE as Global variable.I am using VC++.NET to creat an MFC application.If some one could please
help I'd be grateful.
Thanks
0
Comment
Question by:samroyc
  • 3
  • 2
  • 2
7 Comments
 
LVL 3

Expert Comment

by:mactep13
ID: 13744720
You can declare this as

BYTE array[CONST_SIZE]; in the implementation file of your CWinApp derived class (the cpp file). You will find a declaration of your app there (Usually above InitInstance() function). After you declare your array there, it will be globally accesable to your app. Just remember, if you want to use it, declare it as external in the file you want to use it:

extern BYTE array[CONST_SIZE];

declare it before you use it.

As an alternitive, you can declare it just before or after the definition of the Application class. This will not require you to use extern, but the practice is not very safe. It is quite safe if you use #pragma once directive in that header and not run into circular references.

Also, I would recommend a dynamicly resizable array such as a vector or since you're using MFC, a CArray. Declare it as follows.
CArray<BYTE, BYTE> array1;
Don't forget to include
#include <afxtempl.h> either in stdafx.h or in every file the array will be refernced.

If you have any questions, let me know.
Hope this helps.
mactep
0
 

Author Comment

by:samroyc
ID: 13744831
Thanks,though i can now access the array,trying to initialise it gives the error...
error C2205: 'array' : cannot initialize extern variables with block scope
I need this array so that I can use it as a buffer,into which data from file will be stored.
Here is how I defined the array
// The one and only CLearn_Pointers_MFCApp object

CLearn_Pointers_MFCApp theApp;
BYTE array[512];

// CLearn_Pointers_MFCApp initialization

BOOL CLearn_Pointers_MFCApp::InitInstance()
0
 
LVL 3

Expert Comment

by:mactep13
ID: 13744880
How are you trying to initialize it?

Remember, arrays can NOT be initialized after they are defined using the assignment (=) operator. You must use either memcpy or strcpy to place info in the array. I just ran a sample in the MFC dialog based app and it seems to be working. I have declared the
BYTE array[512]; just like you had.
Then, in my Dialog .cpp file, I have declared the extren BYTE array[512]; at the top. The inside one of my functions, I use:

strcpy((char*)array, "Test Initialization");

This now places the string into array. I ran the sample and it works.

Also, using global variables in a C++ application is usually a very WRONG thing to do. Try rethinking your design. Is it absolutly necessary? If so, explain why...

mactep
0
Concerto's Cloud Advisory Services

Want to avoid the missteps to gaining all the benefits of the cloud? Learn more about the different assessment options from our Cloud Advisory team.

 

Author Comment

by:samroyc
ID: 13745001
I am processing data from a file,and storing the proessed data in a buffer.This is done in a dialog based MFc application,with
a control button.With another control button I wish to send this buffer over the network to a device.
Initially I was writing this buffer into a file and sending it.
I thought making this buffer a global variable I would be able to send it without writing into a file.
I was unaware that one should not use global variables in VC applications-thank you for letting me know that.
If you have any suggestions about how I can send this buffer without making it a global variable,I'd be grateful.
0
 
LVL 3

Accepted Solution

by:
mactep13 earned 2000 total points
ID: 13745065
Place the BYTE array into the dialog class. Make him a class member. Then, any function of the dialog will be able to use him, since he is the member of the class.

class CYourDerivedDlg
{

public:
    Constructor()
  afx_msg functions (if you have any)
    virtual functions (if you have any)

protected:

    BYTE array[512];
};

Then in cpp file:

OnInitDialog()
{

memset(array, 0, 512);         // This will init the array to 0s.
};

OnButtonPressed() // Or something like that
{
  memcpy(array, source, BytesToCopy);
// This will copy BytesToCopy number of bytes from source (which takes a void*, another words, any pointer can be used) to array. Void * can be cast to any pointer, not object. So if you have an object, give the address of it.
Like:

string strData;
memcopy(array, &strData, strData.size());
}

Then, if you have another button or something, you will create a new handler:
OnNextButton() // or something...
{
You can use the array here too as it is declared in class scope

strcpy (array, "Yes I can use him here too", 29);
// I hardcoded 29 because that is the length of the string.
}

That's all. Now that you have declared this in class scope, your object lives while the Dialog class lives. If you have declared him in main dialog, which I suspect you will, the object will be alive until you close the dialog.
I appologize if I gave way to much information and if you know all of this, but I figured more info can not hurt.

Hope this helps.
mactep

By the way, you still did not tell me how you initialized the array. Are you still getting the same error? I was unable to reproduce this.
Thanks.
0
 
LVL 9

Expert Comment

by:rcarlan
ID: 13745177
Of course you can use a global buffer (not that it's the best solution, though ;-)

Somewhere in a header file:

// Buffer.h
extern BYTE g_abyBuffer[];
static const size_t gc_nBufferSize = 1024;   // whatever you think the required maximum size will be
extern size_t g_nBufferPayload;    // this is the number of bytes actually initialised in the buffer

Somewhere in a .cpp file:

// Buffer.cpp
#include "Buffer.h"                 // or whatever you've chosen as a name for the header file
BYTE g_abyBuffer[gc_nBufferSize];
size_t g_nBufferPayload = 0;

In your dialog's .cpp file:

//  MyDialog.cpp
#include "Buffer.cpp"

void CMyDialog::OnProcessButton()
{
    m_bInputFileProcessed = false;  
        // this can be a bool data member in your dialog class to flag whether or not the file was processed successfully

    try
    {
        CFile fInput(m_sInputFile, CFile::modeRead | CFile::shareDenyWrite);
            // m_sInputFile is the path to the file to process (presumably entered by the user in an edit-box in the dialog)

        for (size_t i=0; i<fInput.GetLength(); ++i)
        {
            // todo: replace the code below with your own processing (hopefully larger chunks, not one byte at a time;-)
            BYTE byCurrent;
            fInput.Read(&byCurrent, 1);

            // process byCurrent

            ASSERT(i < gc_nBufferSize);    // otherwise the code below will overrun and possibly cause access violation or corrupt memory)
            g_abyBuffer[i] = byCurrent;
        }
        m_bInputFileProcessed = true;  
        g_nBufferPayload = fInput.GetLength();
    }
    catch (CFileException* pe)
    {
        // error while trying to open the file
        // todo: analyse the error in 'pe' and possibly take some corrective action or give the user additional information
           (i.e. replace the generic error reporting mechanism on the line below)
        pe->ReportError();
        pe->Delete();
    }
    catch (CException* pe)
    {
        // unexpected MFC exception
        // use generic error reporting
        pe->ReportError();
        pe->Delete();
    }
    catch (...)
    {
        // unexpected exception
    }
}


Of course, a better solution is to make your BYTE buffer a member of the dialog class - that is, if you want to send it over the network from within the dialog or before the dialog object is destroyed. If not, you can make it a member of your CWinApp-derived class. You should also consider allocating it dynamically (i.e. new BYTE[]), in which case you can allocate whatever size is required for the file being processed. In this case, you should obviously release the buffer in the destructor (i.e. delete [] ).

Radu
0
 
LVL 9

Expert Comment

by:rcarlan
ID: 13745201
mactep13 beat me to it :-)
I was busy typing away, while he posted his answer.
There's nothing wrong with his solution, so please award the points to him.

The only thing I would suggest is adding a size_t data member to store the actual payload size.
Of course, allocating the buffer dynamically would be better:

// in the header file
BYTE* array;  // in the class declaration

// in the .cpp file
array = NULL;    // in the constructor

...

array = new BYTE[buffer_size];   // before populating the buffer (but once you know how many bytes you need to store)

...

delete [] array;  // in the destructor

Radu
0

Featured Post

Free Tool: SSL Checker

Scans your site and returns information about your SSL implementation and certificate. Helpful for debugging and validating your SSL configuration.

One of a set of tools we are providing to everyone as a way of saying thank you for being a part of the community.

Question has a verified solution.

If you are experiencing a similar issue, please ask a related question

Introduction: Database storage, where is the exe actually on the disc? Playing a game selected randomly (how to generate random numbers).  Error trapping with try..catch to help the code run even if something goes wrong. Continuing from the seve…
Introduction: The undo support, implementing a stack. Continuing from the eigth article about sudoku.   We need a mechanism to keep track of the digits entered so as to implement an undo mechanism.  This should be a ‘Last In First Out’ collec…
This video will show you how to get GIT to work in Eclipse.   It will walk you through how to install the EGit plugin in eclipse and how to checkout an existing repository.
Kernel Data Recovery is a renowned Data Recovery solution provider which offers wide range of softwares for both enterprise and home users with its cost-effective solutions. Let's have a quick overview of the journey and data recovery tools range he…
Suggested Courses

621 members asked questions and received personalized solutions in the past 7 days.

Join the community of 500,000 technology professionals and ask your questions.

Join & Ask a Question