Define_Module() throws an error | C++ | Omnet++ - c++

There is an error in Define_Module(OLT) when i try to build my code.
Am i doing something wrong?
D:\omnetpp-4.6\ptixiaki\XGPON/OLT.cc:18: undefined reference to `OLT::OLT()'
collect2.exe: error: ld returned 1 exit status
make: *** [out/gcc-debug//XGPON.exe] Error 1
Makefile:94: recipe for target 'out/gcc-debug//XGPON.exe' failed
//XGPON.NED
package xgpon;
import ned.DelayChannel;
import ned.IdealChannel;
simple OLT
{
#display("i=device/mainframe");
gates:
input splitter_to_OLT;
output OLT_to_splitter;
}
simple Splitter
{
#display("i=device/modem");
gates:
input ONU_splitter[];
input OLT_splitter;
output splitter_OLT;
output splitter_ONU[];
}
simple ONU
{
#display("i=device/laptop");
gates:
input splitter_to_ONU;
output ONU_to_splitter;
}
network XGPON
{
parameters:
#display("bgb=550,234;i=block/network2");
int n_nodes = 6;
types:
channel upstream extends ned.DatarateChannel
{
datarate = 2.48832 Gbps; //datarate of the channel
}
channel downstream extends ned.DatarateChannel
{
datarate = 9.95328 Gbps; //datarate of the channel
}
submodules:
splitter: Splitter {
#display("p=258,109");
}
olt: OLT {
#display("p=57,59");
}
onu: ONU {
#display("p=393,87");
}
connections:
olt.OLT_to_splitter --> downstream -->splitter.OLT_splitter;
splitter.splitter_OLT --> downstream --> onu.splitter_to_ONU;
splitter.splitter_ONU++ --> upstream --> olt.splitter_to_OLT;
onu.ONU_to_splitter --> upstream --> splitter.ONU_splitter++;
}
//OLT.H
#ifndef OLT_H_
#define OLT_H_
#include <omnetpp.h>
#include <string.h>
#include <iostream>
#include <stdio.h>
#include "Packet_m.h"
#include "DownstreamFrame_m.h"
#include "UpstreamFrame_m.h"
#define FRAME_TIME 691.2
class OLT : public cSimpleModule
{
private:
int source;
//int destination;
simsignal_t arrivalSignal;
int no_sent;
int no_rcvd;
cMessage *DownstreamFrameSendEvent, *NewPacketArrivalEvent;
simtime_t sendTimeout, bufferTimeout;
XGPONpacket *downFragment;
cPacketQueue *OLTBuffer;
std::vector<double> distance, RTT, BandwidthUtilizationProfile, AllocationWeight;
//std::vector<long double> accumulatedRequestedBandwidth , accumulatedAllocatedBandwidth;
std:: vector<int> upstreamBandwidthDemands, DownPacketsForONU, destination;
int oltId, numberOfOnus, headerSize, PSBd, parityBytes, PLOAMdMessages, FrameQueueSize, fragmentBytes, BWMap;
//int FixedGuarandeedBandwidth, totalUpstreamBandwidth, AssuredGuarandeedBandwidth, firstPhaseNonGuarandeedBandwidth;
//long double totalBytesCreated, totalBytesReceived, SumDelay, SquareSumDelay, totalUpDelay, SumBUP;
//double ABU, ProtectionParameter, OverloadedOnusAllocationWeighSum, UpdatingImpact, SW;
double ONU_time_counter ; /* a local time counter for file results */
double variate; /* the final exponenetial variate (interarrivals) */
double sum_variate ; /* used to compute the experimental mean for variate */
double sum_rnd; /* used to compute the experimental mean for UD */
long loops ; /* counter for loops */
long pkt_per_time_unit ; /* nb of pkts per unit of time */
double time; /* our simulated time in us */
double mean,start_pktime,ref_time,end_pktime;
double rnd_nb; /* the uniform random number */
public :
OLT();
virtual ~OLT();
protected:
virtual void initialize();
virtual void handleMessage(cMessage *msg);
virtual XGPONpacket *generatePacket();
virtual void generateFrame(cPacketQueue *queue);
//virtual void generateHeader(cPacketQueue *queue);
virtual void forwardFrame(XGPONpacket *msg);
virtual void finish();
//virtual int defragmentation(cPacketQueue *queue);
};
#endif /* OLT_H_ */
//OLT.CC
#include "OLT.h"
Define_Module(OLT); //the error is here
void OLT::initialize()
{
numberOfOnus = 6;
cPacketQueue* OLTBuffer = new cPacketQueue("OLTBuffer");
for(int i = 0; i<= numberOfOnus; i++){
OLTBuffer->insert(generatePacket());
XGPONpacket *packet = (XGPONpacket *) OLTBuffer->pop();
//Distance
distance.push_back(destination.at(i) + 20);
EV << "My distance is " << distance[i] << " numbers.\n \n";
EV << "My destination is " << packet->getDestination()/2 << ".\n \n";
//RTT
RTT.push_back(distance.at(i) / 3*(10^8));
EV << "My RTT is " << RTT[i] << " numbers.\n \n";
}
EV << "My buffer size is " << OLTBuffer->getLength() << " numbers.\n \n";
//generateFrame(OLTBuffer);
}
void OLT::handleMessage(cMessage *msg)
{
XGPONpacket *ttmsg = check_and_cast<XGPONpacket *>(msg);
forwardFrame(ttmsg);
}
void OLT::generateFrame(cPacketQueue *OLTBuffer)
{
DownFrame *queue = new DownFrame();
//Fmqueue Fmqueue;
queue->~DownFrame();
//FrameQueueSize = queue -> getFrameSize();
//cPacketQueue *queue = new cPacketQueue();
//FrameQueueSize = 155520;
for(int i=0 ; i <OLTBuffer->getLength(); i++)
{
//EV << "GAMW TI MANA SOU " << OLTBuffer->getLength() << " numbers.\n \n";
XGPONpacket *packet = (XGPONpacket *) OLTBuffer->pop();
simtime_t waitingTime = simTime() - packet->getCreationTime();
double processTime = (packet->getBitLength()/(9.95328 * pow (10,9))) + (RTT.at(packet->getDestination())/2);
simtime_t receptTime = waitingTime + processTime;
packet->setReceptionTime(receptTime);
EV << "<<<<<<< OLT (id =" << oltId << ") : Packet " << packet->getName() << "reception time:" << packet->getReceptionTime() << ">>>>> \n";
OLTBuffer -> insert(packet);
}
while ((queue->getByteLength() < FrameQueueSize) && (OLTBuffer->isEmpty() == false))
{
XGPONpacket *max = (XGPONpacket *) OLTBuffer->pop();
for(int i=0; i<OLTBuffer->length(); i++)
{
XGPONpacket *data = (XGPONpacket *) OLTBuffer->pop();
if(max->getReceptionTime() >= data->getReceptionTime())
{
OLTBuffer -> insert(data);
}
else
{
OLTBuffer->insert(max);
max = data->dup();
delete data;
}
}
EV <<"<<<< OLT (id =" << oltId <<") : Packet " << max->getName() << " reception time:" << max->getReceptionTime() << "inserted to frame >>>>\n";
queue->insert(max);
}
}
XGPONpacket *OLT::generatePacket()
{
// Produce source and destination addresses.
//source = getIndex(); // our module index
//Destinationn
int time_limit = 60;
for(source = 1; source <= numberOfOnus-1; source++)
{
ONU_time_counter = 0;
pkt_per_time_unit = 0;
sum_variate = 0;
sum_rnd = 0;
loops = 0;
time=0;
destination.push_back(intuniform(2,numberOfOnus-1));
start_pktime=0.7;
end_pktime=12.7; //1gb prepei na brw transmision time
mean = start_pktime;
ref_time = time;
while( time < time_limit )
{
if(ONU_time_counter >= FRAME_TIME)
{
mean = (double) mean +(end_pktime - start_pktime)/((time_limit - ref_time)/FRAME_TIME);
ONU_time_counter = ONU_time_counter - FRAME_TIME;
/* prints the nb of pkts / unit time */
//fprintf(files1, "\n%ld", pkt_per_time_unit);
pkt_per_time_unit = 0;
}
//rnd_nb = (random()/limit); /* the random number 0<= x <=1 */
rnd_nb = uniform(0,1);
/* compute the IAT */
variate = (-mean)*log(rnd_nb); /* Poisson IAT */
//wait(variate);
XGPONpacket *msg = new XGPONpacket();
msg->setSource(source);
msg->setDestination(destination[source]);
msg->setByteLength(intuniform(64,1518));
return msg;
}
}
}
void OLT::forwardFrame(XGPONpacket *msg)
{
// Same routing as before: random gate.
int n = gateSize("out");
//int k = destination;
//EV << "Forwarding message " << msg << " on gate[" << k << "]\n";
send(msg, "out");
}
void OLT::finish()
{
//recordScalar("#sent", no_sent);
//recordScalar("received", no_rcvd);
}

In OLT.CC add at least an empty constructor and destructor:
OLT::OLT() {
}
OLT::~OLT() {
}

Related

broadcast a message in omnet++ with timestamp

I m trying to broadcast a message to multiple nodes from one node then the receiving nodes will broadcast the message between each other , this message will include a timestamp , this is my cc file code , can anyone help me to know what to fix or to add, thank you
`
void Res::initialize()
{
// TODO - Generated method body
seq=0;
signalID = registerSignal("arrival");
timestamp = 1;
if (getIndex() == 0) {
//Boot the process scheduling the initial message as a self-message.
char msgname[20];
sprintf(msgname, "node-%d", getIndex());
cMessage *msg = new cMessage(msgname);
scheduleAt(0.0, msg);
}
}
void Res::handleMessage(cMessage *msg)
{
if (getIndex() == 3) {
// Message arrived.
EV << "Message " << msg << " arrived.\n";
delete msg;
} else {
forwardMessage(msg);
}
}
void Res::forwardMessage(cMessage *msg)
{
int n = gateSize("out");
int k = intuniform(0, n-1);
EV << "Forwarding message " << msg << " on port out [" << k << "]\n";
for (int i = 0; i < n; i++)
{
cTimestampedValue tmp(timestamp, msg);
emit(signalID, &tmp);
cMessage *copy = msg->dup();
send(copy, "out", i);
}
}
`

Multiple Definitions Error of Global Arrays [duplicate]

This question already has answers here:
c++ multiple definitions of a variable
(5 answers)
multiple definition error c++
(2 answers)
What exactly is One Definition Rule in C++?
(1 answer)
Closed 2 years ago.
I am attempting to compile my c++ code, and I continue getting the error:
/tmp/ccEsZppG.o:(.bss+0x0): multiple definition of `mailboxes'
/tmp/ccEZq43v.o:(.bss+0x0): first defined here
/tmp/ccEsZppG.o:(.bss+0xc0): multiple definition of `threads'
/tmp/ccEZq43v.o:(.bss+0xc0): first defined here
/tmp/ccEsZppG.o:(.bss+0x120): multiple definition of `semaphores'
/tmp/ccEZq43v.o:(.bss+0x120): first defined here
collect2: error: ld returned 1 exit status
Here is my code:
addem.cpp
#include <stdio.h>
#include <iostream>
#include <stdlib.h>
#include <semaphore.h>
#include <pthread.h>
#include "mailbox.h"
using namespace std;
void *sumUp(void *arg);
int main(int argc, char *argv[]) {
int numThreads, minThreads, maxInt, minInt;
if (argc < 3) {
cout << "Error: Need three arguments" << endl;
return 1;
}
numThreads = atoi(argv[1]);
maxInt = atoi(argv[2]);
minThreads = 1;
minInt = 1;
if (numThreads < 1) {
cout << "Cannot work with less than one thread\n"
<< "It's okay but do better next time!\n"
<< "We'll work with 1 thread this time.\n";
numThreads = minThreads;
} else if (numThreads > MAXTHREAD) {
cout << "Sorry, the max for threads is 10.\n"
<< "We'll work with 10 threads this time.\n";
numThreads = MAXTHREAD;
}
if (maxInt < 1) {
cout << "What do you want me to do? I can't count backwards!\n"
<< "I can barely count forwards! Let's make the max number\n"
<< "be 1 to save time\n";
maxInt = minInt;
}
struct msg outgoingMail[numThreads];
int divider = maxInt / numThreads;
int count = 1;
//initialize arrays (mailboxes, semaphores)
for (int i = 0; i < numThreads; i++) {
sem_init(&semaphores[i], 0, 1);
outgoingMail[i].iSender = 0;
outgoingMail[i].type = RANGE;
outgoingMail[i].value1 = count;
count = count + divider;
if (i = numThreads - 1) {
outgoingMail[i].value2 = maxInt;
} else {
outgoingMail[i].value2 = count;
}
}
for (int message = 0; message < numThreads; message++) {
SendMsg(message+1, outgoingMail[message]);
}
int thread;
for (thread = 0; thread <= numThreads; thread++) {
pthread_create(&threads[thread], NULL, &sumUp, (void *)(intptr_t)(thread+1));
}
struct msg incomingMsg;
int total = 0;
for (thread = 0; thread < numThreads; thread++) {
RecvMsg(0, incomingMsg);
total = total + incomingMsg.value1;
}
cout << "The total for 1 to " << maxInt << " using "
<< numThreads << " threads is " << total << endl;
return 0;
}
void *sumUp(void *arg) {
int index,total;
index = (intptr_t)arg;
struct msg message;
RecvMsg(index, message);
message.iSender = index;
message.type = ALLDONE;
total = 0;
for (int i = message.value1; i <= message.value2; i++) {
total += i;
}
SendMsg(0, message);
return (void *) 0;
}
mailbox.cpp
#include <stdio.h>
#include <iostream>
#include "mailbox.h"
using namespace std;
int SendMsg(int iTo, struct msg &Msg) {
if (safeToCall(iTo)) {
cout << "Error calling SendMsg" << endl;
return 1;
}
sem_wait(&semaphores[iTo]);
mailboxes[iTo] = Msg;
sem_post(&semaphores[iTo]);
return 0;
}
int RecvMsg(int iFrom, struct msg &Msg) {
sem_wait(&semaphores[iFrom]);
if (safeToCall(iFrom)) {
cout << "Error calling RecvMsg" << endl;
return 1;
}
mailboxes[iFrom] = Msg;
sem_post(&semaphores[iFrom]);
return 0;
}
bool safeToCall(int location) {
bool safe = !(location < 0 || location > MAXTHREAD + 1);
return safe;
//return true;
}
mailbox.h
#ifndef MAILBOX_H_
#define MAILBOX_H_
#define RANGE 1
#define ALLDONE 2
#define MAXTHREAD 10
#include <semaphore.h>
#include <pthread.h>
struct msg {
int iSender; /* sender of the message (0 .. numThreads)*/
int type; /* its type */
int value1; /* first value */
int value2; /* second value */
};
struct msg mailboxes[MAXTHREAD + 1];
pthread_t threads[MAXTHREAD + 1];
sem_t semaphores[MAXTHREAD + 1];
int SendMsg(int iTo, struct msg &Msg);
int RecvMsg(int iFrom, struct msg &Msg);
bool safeToCall(int location);
#endif
I am compiling the code with the command
g++ -o addem addem.cpp mailbox.cpp -lpthread
I have tried commenting out all of the function bodies in the source code to leave them as stub functions, and the same error occurs. The only way I have been able to compile the file is if I comment out the function bodies, and remove
#include "mailbox.h"
From at least one of the files. I feel it has to do with how I am initializing the arrays? But I cannot figure out a workaround.

Mxnet c++ inference with MXPredSetInput segmentation fault

Mxnet c++ inference with MXPredSetInput segmentation fault
1. background
I have tried https://github.com/apache/incubator-mxnet/tree/master/example/image-classification/predict-cpp successed.
But when I try to deploy mxnet in c++ with my own model, I met a segmentation fault error:
[17:33:07] src/nnvm/legacy_json_util.cc:209: Loading symbol saved by previous version v1.2.1. Attempting to upgrade...
Signal: SIGSEGV (Segmentation fault)
2. code with error:
MXPredSetInput(pred_hnd, "data", image_data.data(), static_cast<mx_uint>(image_size));
3. tips
First I thought it's because of input data shape not compatible with the model input layer.But I ask model designer, it's a resnet model with conv only, so, any kind input shape should be OK.
4. Download model:
Download them, and put them into model dir.
https://drive.google.com/drive/folders/16MEKNOz_iwquVxHMk9c7igmBNuT6w7wz?usp=sharing
4. code: find: https://github.com/jaysimon/mxnet_cpp_infere
#include <cstdio>
#include <cstdlib>
#include <iostream>
#include <fstream>
#include <vector>
#include <memory>
#include <thread>
#include <iomanip>
#include <opencv2/opencv.hpp>
// Path for c_predict_api
#include <mxnet/c_predict_api.h>
const mx_float DEFAULT_MEAN = 117.0;
static std::string trim(const std::string& input) {
auto not_space = [](int ch) {
return !std::isspace(ch);
};
auto output = input;
output.erase(output.begin(), std::find_if(output.begin(), output.end(), not_space));
output.erase(std::find_if(output.rbegin(), output.rend(), not_space).base(), output.end());
return output;
}
// Read file to buffer
class BufferFile {
public :
std::string file_path_;
std::size_t length_ = 0;
std::unique_ptr<char[]> buffer_;
explicit BufferFile(const std::string& file_path)
: file_path_(file_path) {
std::ifstream ifs(file_path.c_str(), std::ios::in | std::ios::binary);
if (!ifs) {
std::cerr << "Can't open the file. Please check " << file_path << ". \n";
return;
}
ifs.seekg(0, std::ios::end);
length_ = static_cast<std::size_t>(ifs.tellg());
ifs.seekg(0, std::ios::beg);
std::cout << file_path.c_str() << " ... " << length_ << " bytes\n";
// Buffer as null terminated to be converted to string
buffer_.reset(new char[length_ + 1]);
buffer_[length_] = 0;
ifs.read(buffer_.get(), length_);
ifs.close();
}
std::size_t GetLength() {
return length_;
}
char* GetBuffer() {
return buffer_.get();
}
};
void GetImageFile(const std::string& image_file,
mx_float* image_data, int channels,
cv::Size resize_size, const mx_float* mean_data = nullptr) {
// Read all kinds of file into a BGR color 3 channels image
cv::Mat im_ori = cv::imread(image_file, cv::IMREAD_COLOR);
if (im_ori.empty()) {
std::cerr << "Can't open the image. Please check " << image_file << ". \n";
assert(false);
}
cv::Mat im;
resize(im_ori, im, resize_size);
int size = im.rows * im.cols * channels;
mx_float* ptr_image_r = image_data;
mx_float* ptr_image_g = image_data + size / 3;
mx_float* ptr_image_b = image_data + size / 3 * 2;
float mean_b, mean_g, mean_r;
mean_b = mean_g = mean_r = DEFAULT_MEAN;
mean_b = 103.06;
mean_g = 115.9;
mean_r = 123.15;
for (int i = 0; i < im.rows; i++) {
auto data = im.ptr<uchar>(i);
for (int j = 0; j < im.cols; j++) {
if (channels > 1) {
*ptr_image_b++ = static_cast<mx_float>(*data++) - mean_b;
*ptr_image_g++ = static_cast<mx_float>(*data++) - mean_g;
}
*ptr_image_r++ = static_cast<mx_float>(*data++) - mean_r;
}
}
}
// LoadSynsets
// Code from : https://github.com/pertusa/mxnet_predict_cc/blob/master/mxnet_predict.cc
std::vector<std::string> LoadSynset(const std::string& synset_file) {
std::ifstream fi(synset_file.c_str());
if (!fi.is_open()) {
std::cerr << "Error opening synset file " << synset_file << std::endl;
assert(false);
}
std::vector<std::string> output;
std::string synset, lemma;
while (fi >> synset) {
getline(fi, lemma);
output.push_back(lemma);
}
fi.close();
return output;
}
void PrintOutputResult(const std::vector<float>& data, const std::vector<std::string>& synset) {
if (data.size() != synset.size()) {
std::cerr << "Result data and synset size do not match!" << std::endl;
}
float best_accuracy = 0.0;
std::size_t best_idx = 0;
for (std::size_t i = 0; i < data.size(); ++i) {
std::cout << "Accuracy[" << i << "] = " << std::setprecision(8) << data[i] << std::endl;
if (data[i] > best_accuracy) {
best_accuracy = data[i];
best_idx = i;
}
}
std::cout << "Best Result: " << trim(synset[best_idx]) << " (id=" << best_idx << ", " <<
"accuracy=" << std::setprecision(8) << best_accuracy << ")" << std::endl;
}
void predict(PredictorHandle pred_hnd, const std::vector<mx_float> &image_data,
NDListHandle nd_hnd, const std::string &synset_file, int i) {
auto image_size = image_data.size();
// Set Input
//>>>>>>>>>>>>>>>>>>>> Problem code <<<<<<<<<<<<<<<<<<<<<<<
MXPredSetInput(pred_hnd, "data", image_data.data(), static_cast<mx_uint>(image_size));
// <<<<<<<<<<<<<<<<<<<<<<< Problem code <<<<<<<<<<<<<<<<<<<<<<<
// Do Predict Forward
MXPredForward(pred_hnd);
mx_uint output_index = 0;
mx_uint* shape = nullptr;
mx_uint shape_len;
// Get Output Result
MXPredGetOutputShape(pred_hnd, output_index, &shape, &shape_len);
std::size_t size = 1;
for (mx_uint i = 0; i < shape_len; ++i) { size *= shape[i]; }
std::vector<float> data(size);
MXPredGetOutput(pred_hnd, output_index, &(data[0]), static_cast<mx_uint>(size));
// Release NDList
if (nd_hnd) {
MXNDListFree(nd_hnd);
}
// Release Predictor
MXPredFree(pred_hnd);
// Synset path for your model, you have to modify it
auto synset = LoadSynset(synset_file);
// Print Output Data
PrintOutputResult(data, synset);
}
int main(int argc, char* argv[]) {
if (argc < 2) {
std::cout << "No test image here." << std::endl
<< "Usage: ./image-classification-predict apple.jpg [num_threads]" << std::endl;
return EXIT_FAILURE;
}
std::string test_file(argv[1]);
int num_threads = 1;
if (argc == 3)
num_threads = std::atoi(argv[2]);
// Models path for your model, you have to modify it
std::string json_file = "../model/rfcn_dcn_chicken-0000.json";
std::string param_file = "../model/rfcn_dcn_chicken-0000.params";
std::string synset_file = "../model/synset.txt";
std::string nd_file = "../model/mean_224.nd";
BufferFile json_data(json_file);
BufferFile param_data(param_file);
// Parameters
int dev_type = 1; // 1: cpu, 2: gpu
int dev_id = 0; // arbitrary.
mx_uint num_input_nodes = 1; // 1 for feedforward
const char* input_key[1] = { "data" };
const char** input_keys = input_key;
// Image size and channels
int width = 1000;
int height = 562;
int channels = 3;
const mx_uint input_shape_indptr[2] = { 0, 4 };
const mx_uint input_shape_data[4] = { 1,
static_cast<mx_uint>(channels),
static_cast<mx_uint>(height),
static_cast<mx_uint>(width) };
if (json_data.GetLength() == 0 || param_data.GetLength() == 0) {
return EXIT_FAILURE;
}
auto image_size = static_cast<std::size_t>(width * height * channels);
// Read Mean Data
const mx_float* nd_data = nullptr;
NDListHandle nd_hnd = nullptr;
BufferFile nd_buf(nd_file);
if (nd_buf.GetLength() > 0) {
mx_uint nd_index = 0;
mx_uint nd_len;
const mx_uint* nd_shape = nullptr;
const char* nd_key = nullptr;
mx_uint nd_ndim = 0;
MXNDListCreate(static_cast<const char*>(nd_buf.GetBuffer()),
static_cast<int>(nd_buf.GetLength()),
&nd_hnd, &nd_len);
MXNDListGet(nd_hnd, nd_index, &nd_key, &nd_data, &nd_shape, &nd_ndim);
}
// Read Image Data
std::vector<mx_float> image_data(image_size);
GetImageFile(test_file, image_data.data(), channels, cv::Size(width, height), nd_data);
if (num_threads == 1) {
// Create Predictor
PredictorHandle pred_hnd;
MXPredCreate(static_cast<const char*>(json_data.GetBuffer()),
static_cast<const char*>(param_data.GetBuffer()),
static_cast<int>(param_data.GetLength()),
dev_type,
dev_id,
num_input_nodes,
input_keys,
input_shape_indptr,
input_shape_data,
&pred_hnd);
assert(pred_hnd);
predict(pred_hnd, image_data, nd_hnd, synset_file, 0);
} else {
// Create Predictor
std::vector<PredictorHandle> pred_hnds(num_threads, nullptr);
MXPredCreateMultiThread(static_cast<const char*>(json_data.GetBuffer()),
static_cast<const char*>(param_data.GetBuffer()),
static_cast<int>(param_data.GetLength()),
dev_type,
dev_id,
num_input_nodes,
input_keys,
input_shape_indptr,
input_shape_data,
pred_hnds.size(),
pred_hnds.data());
for (auto hnd : pred_hnds)
assert(hnd);
std::vector<std::thread> threads;
for (int i = 0; i < num_threads; i++)
threads.emplace_back(predict, pred_hnds[i], image_data, nd_hnd, synset_file, i);
for (int i = 0; i < num_threads; i++)
threads[i].join();
}
printf("run successfully\n");
return EXIT_SUCCESS;
}

"pBase not defined"? pBase is defined in the included class

This program is supposed to read acceleration values from a Wii remote and light up LEDs based on those values. The only error I'm getting that prevents compilation is that pBase isn't defined in main.cpp. main.cpp includes ZedBoard.h and ZedBoard.cpp where pBase is defined so I'm failing to see the issue here. I've been trying to solve this for a while and I can't figure it out.
ZedBoard.h
#ifndef ZEDBOARD_H
#define ZEDBOARD_H
const int gpio_led1_offset = 0x12C; // Offset for LED1
const int gpio_led2_offset = 0x130; // Offset for LED2
const int gpio_led3_offset = 0x134; // Offset for LED3
const int gpio_led4_offset = 0x138; // Offset for LED4
const int gpio_led5_offset = 0x13C; // Offset for LED5
const int gpio_led6_offset = 0x140; // Offset for LED6
const int gpio_led7_offset = 0x144; // Offset for LED7
const int gpio_led8_offset = 0x148; // Offset for LED8
const int gpio_sw1_offset = 0x14C; // Offset for Switch 1
const int gpio_sw2_offset = 0x150; // Offset for Switch 2
const int gpio_sw3_offset = 0x154; // Offset for Switch 3
const int gpio_sw4_offset = 0x158; // Offset for Switch 4
const int gpio_sw5_offset = 0x15C; // Offset for Switch 5
const int gpio_sw6_offset = 0x160; // Offset for Switch 6
const int gpio_sw7_offset = 0x164; // Offset for Switch 7
const int gpio_sw8_offset = 0x168; // Offset for Switch 8
const int gpio_pbtnl_offset = 0x16C; // Offset for left push button
const int gpio_pbtnr_offset = 0x170; // Offset for right push button
const int gpio_pbtnu_offset = 0x174; // Offset for up push button
const int gpio_pbtnd_offset = 0x178; // Offset for down push button
const int gpio_pbtnc_offset = 0x17C; // Offset for center push button
// Physical base address of GPIO
const unsigned gpio_address = 0x400d0000;
// Length of memory-mapped IO window
const unsigned gpio_size = 0xff;
// Class Definition
class ZedBoard {
private:
char *pBase; // virtual address where I/O was mapped
int fd; // file descriptor for dev memory
int dummyValue; // for testing without a Zedboard
public:
ZedBoard(); // Default Constructor
~ZedBoard(); // Destructor
void RegisterWrite(char *pBase, int offset, int value);
int RegisterRead(int offset);
void Write1Led(char *pBase, int ledNum, int state);
void WriteAllLeds(int value);
int Read1Switch(int switchNum);
int ReadAllSwitches();
};
#endif
ZedBoard.cpp
#include <stdlib.h>
#include <fcntl.h>
#include <unistd.h>
#include <sys/mman.h>
#include <iostream>
#include "ZedBoard.h"
using namespace std;
/**
* Constructor Initialize general-purpose I/O
* - Opens access to physical memory /dev/mem
* - Maps memory at offset 'gpio_address' into virtual address space
*
* #param None Default constructor does not need arguments.
* #return None Default constructor does not return anything.
*/
ZedBoard::ZedBoard(){
cout << "\nStarting...." << endl;
// dummyValue = 99;
// Uncomment this block of code when connected to the Zedboard
fd = open( "/dev/mem", O_RDWR);
pBase = (char *) mmap(NULL,gpio_size,PROT_READ | PROT_WRITE,
MAP_SHARED,fd,gpio_address);
// Check error
if (pBase == MAP_FAILED)
{
cerr << "Mapping I/O memory failed - Did you run with 'sudo'? \n";
exit(1); // Returns 1 to the operating system;
}
}
/**
* Destructor to close general-purpose I/O.
* - Uses virtual address where I/O was mapped.
* - Uses file descriptor previously returned by 'open'.
*
* #param None Destructor does not need arguments.
* #return None Destructor does not return anything.
*/
ZedBoard::~ZedBoard(){
munmap(pBase, gpio_size);
}
/*
* Write a 4-byte value at the specified general-purpose I/O location.
*
* - Uses base address returned by 'mmap'.
* #parem offset Offset where device is mapped.
* #param value Value to be written.
*/
void ZedBoard::RegisterWrite(char *pBase, int offset, int value)
{
* (int *) (pBase + offset) = value;
// dummyValue = value;
}
/**
* Read a 4-byte value from the specified general-purpose I/O location.
- Uses base address returned by 'mmap'.
#param offset Offset where device is mapped.
#return Value read.
*/
int ZedBoard::RegisterRead(int offset)
{
return * (int *) (pBase + offset);
// return dummyValue;
}
/*
Changes the state of an LED (ON or OFF)
- Uses base address of I/O
#param ledNum LED number (0 to 7)
#param state State to change to (ON or OFF)
*/
/*
Show lower 8 bits of integer value on LEDs
- Calls Write1Led() to set all LEDs
#param value Value to show on LEDs
*/
void ZedBoard::WriteAllLeds(int value)
{
cout << "\nWriting to all LEDs...." << endl;
for(int i = 0; i < 8; i++) {// write to all LEDs
Write1Led(pBase, i, (value / (1<<i)) % 2);
}
}
void ZedBoard::Write1Led(char *pBase, int ledNum, int state)
{
cout << "\nWriting to LED " << ledNum << ": LED state = " << state << endl;
if (ledNum == 1)
{
RegisterWrite(pBase, gpio_led1_offset, state);
}
else
{
RegisterWrite(pBase, gpio_led1_offset + (ledNum * 4), state);
}
}
/*
Reads the value of a switch
- Uses base address of I/O
#param switchNum Switch number (0 to 7)
#return Switch value read
*/
int ZedBoard::Read1Switch(int switchNum)
{
cout << "\nReading Switch " << switchNum << endl;
//return RegisterRead(gpio_sw1_offset + (switchNum * 4));
return switchNum;
}
/*
Reads the switch values into a decimal integer
- Calls Read1Switch() to read all switches
#return Switches' value read
*/
int ZedBoard::ReadAllSwitches()
{
int switchValue = 0;
cout << "\nReading all switches...." << endl;
for(int i = 7; i >= 0; i--) {// read all switches
switchValue = (switchValue << 1) + Read1Switch(i);
}
return switchValue;
}
WiimoteAccel.h
#ifndef WIIMOTEACCEL_H
#define WIIMOTEACCEL_H
class WiimoteAccel{
public:
WiimoteAccel();
~WiimoteAccel();
void Wiimote();
void Listen();
virtual void AccelerationEvent(int code, int acceleration);
private:
int fd;
};
#endif
WiimoteAccel.cpp
#include <stdlib.h>
#include <fcntl.h>
#include <unistd.h>
#include <iostream>
#include "ZedBoard.h"
#include "WiimoteAccel.h"
WiimoteAccel::WiimoteAccel()
{
}
WiimoteAccel::~WiimoteAccel()
{
}
void WiimoteAccel::Wiimote()
{
fd = open("/dev/input/event0", O_RDONLY);
if (fd == -1)
{
std::cerr << "Error: Could not open event file - forgot sudo?\n";
exit(1);
}
}
void WiimoteAccel::Listen()
{
for (;;)
{
// Read a packet of 16 bytes from Wiimote
char buffer[16];
read(fd, buffer, 16);
// Extract code (byte 10) and value (byte 12) from packet
int code = buffer[10];
short acceleration = * (short *) (buffer + 12);
this->AccelerationEvent(code, acceleration);
}
}
void WiimoteAccel::AccelerationEvent(int code, int acceleration)
{
// Print them
std::cout << "Code = " << code << ", acceleration = " << acceleration << '\n';
}
main.cpp
#include <stdlib.h>
#include <fcntl.h>
#include <unistd.h>
#include <iostream>
#include "WiimoteAccel.h"
#include "ZedBoard.h"
#include "ZedBoard.cpp"
using namespace std;
class WiimoteToLed : public WiimoteAccel {
private:
ZedBoard* zed_board;
public:
WiimoteToLed(ZedBoard* zed_board);
~WiimoteToLed();
void AccelerationEvent(int code, int acceleration)
{
int x = 0;
for(;;)
{
if (code == 3)
{
cout << "ACCELERATION IS "<< acceleration <<"!\n";
if(acceleration == 0)
{
x = 0;
}
else if(acceleration > -100 && acceleration <= -75)
{
x = 1;
}
else if(acceleration > -75 && acceleration <= -50)
{
x = 2;
}
else if(acceleration > -50 && acceleration <= -25)
{
x = 3;
}
else if(acceleration > -25 && acceleration > 0)
{
x = 4;
}
else if(acceleration < 0 && acceleration >= 25)
{
x = 5;
}
else if(acceleration < 25 && acceleration >= 50)
{
x = 6;
}
else if(acceleration < 50 && acceleration >= 75)
{
x = 7;
}
else if(acceleration < 75 && acceleration >= 100)
{
x = 8;
}
switch(x)
{
case 0:
cout << "Wiimote isn't moving\n";
zed_board->Write1Led(pBase,1,0);
zed_board->Write1Led(pBase,2,0);
zed_board->Write1Led(pBase,3,0);
zed_board->Write1Led(pBase,4,0);
zed_board->Write1Led(pBase,5,0);
zed_board->Write1Led(pBase,6,0);
zed_board->Write1Led(pBase,7,0);
zed_board->Write1Led(pBase,8,0);
case 1:
zed_board->Write1Led(pBase,1,1);
zed_board->Write1Led(pBase,2,0);
zed_board->Write1Led(pBase,3,0);
zed_board->Write1Led(pBase,4,0);
zed_board->Write1Led(pBase,5,0);
zed_board->Write1Led(pBase,6,0);
zed_board->Write1Led(pBase,7,0);
zed_board->Write1Led(pBase,8,0);
case 2:
zed_board->Write1Led(pBase,1,1);
zed_board->Write1Led(pBase,2,1);
zed_board->Write1Led(pBase,3,0);
zed_board->Write1Led(pBase,4,0);
zed_board->Write1Led(pBase,5,0);
zed_board->Write1Led(pBase,6,0);
zed_board->Write1Led(pBase,7,0);
zed_board->Write1Led(pBase,8,0);
case 3:
zed_board->Write1Led(pBase,1,1);
zed_board->Write1Led(pBase,2,1);
zed_board->Write1Led(pBase,3,1);
zed_board->Write1Led(pBase,4,0);
zed_board->Write1Led(pBase,5,0);
zed_board->Write1Led(pBase,6,0);
zed_board->Write1Led(pBase,7,0);
zed_board->Write1Led(pBase,8,0);
case 4:
zed_board->Write1Led(pBase,1,1);
zed_board->Write1Led(pBase,2,1);
zed_board->Write1Led(pBase,3,1);
zed_board->Write1Led(pBase,4,1);
zed_board->Write1Led(pBase,5,0);
zed_board->Write1Led(pBase,6,0);
zed_board->Write1Led(pBase,7,0);
zed_board->Write1Led(pBase,8,0);
case 5:
zed_board->Write1Led(pBase,1,1);
zed_board->Write1Led(pBase,2,1);
zed_board->Write1Led(pBase,3,1);
zed_board->Write1Led(pBase,4,1);
zed_board->Write1Led(pBase,5,1);
zed_board->Write1Led(pBase,6,0);
zed_board->Write1Led(pBase,7,0);
zed_board->Write1Led(pBase,8,0);
case 6:
zed_board->Write1Led(pBase,1,1);
zed_board->Write1Led(pBase,2,1);
zed_board->Write1Led(pBase,3,1);
zed_board->Write1Led(pBase,4,1);
zed_board->Write1Led(pBase,5,1);
zed_board->Write1Led(pBase,6,1);
zed_board->Write1Led(pBase,7,0);
zed_board->Write1Led(pBase,8,0);
case 7:
zed_board->Write1Led(pBase,1,1);
zed_board->Write1Led(pBase,2,1);
zed_board->Write1Led(pBase,3,1);
zed_board->Write1Led(pBase,4,1);
zed_board->Write1Led(pBase,5,1);
zed_board->Write1Led(pBase,6,1);
zed_board->Write1Led(pBase,7,1);
zed_board->Write1Led(pBase,8,0);
case 8:
zed_board->Write1Led(pBase,1,1);
zed_board->Write1Led(pBase,2,1);
zed_board->Write1Led(pBase,3,1);
zed_board->Write1Led(pBase,4,1);
zed_board->Write1Led(pBase,5,1);
zed_board->Write1Led(pBase,6,1);
zed_board->Write1Led(pBase,7,1);
zed_board->Write1Led(pBase,8,1);
default:
cout << "Code = " << code <<'\n';
}
}
else
{
continue;
}
}
}
};
WiimoteToLed::WiimoteToLed(ZedBoard* zed_board)
{
Wiimote();
}
WiimoteToLed::~WiimoteToLed()
{
}
int main()
{
// Instantiate ZedBoard object statically
ZedBoard zed_board;
// Instantiate WiimoteToLed object statically, passing a pointer to the
// recently created ZedBoard object.
WiimoteToLed wiimote_to_led(&zed_board);
// Enter infinite loop listening to events. The overridden function
// WiimoteToLed::AccelerationEvent() will be invoked when the user moves
// the Wiimote.
wiimote_to_led.Listen();
// Unreachable code, previous function has an infinite loop
return 0;
}
makefile
WiimoteAccel: main.o WiimoteAccel.o
g++ main.o WiimoteAccel.o -o WiimoteAccel
main.o: main.cpp WiimoteAccel.h
g++ -g -Wall -c main.cpp
WiimoteAccel.o: WiimoteAccel.cpp WiimoteAccel.h
g++ -g -Wall -c WiimoteAccel.cpp
clean:
rm main.o WiimoteAccel.o WiimoteAccel
In WiimoteToLed::AccelerationEvent you call
zed_board->Write1Led(pBase,1,1);
but pBase is not declared in this scope. You have a pBase member of the zed_board, but that is a different one.

error in wrapping class for dll functions

I have a 3rd party .dll (and relative .h and .lib) to control a device via USB.
I want to use the dll functions into a class (AOTF_controller) to implement my desired behaviour.
What I want to do is :
Connect to the device (connect() class function);
Initialize it (init() class function);
Set some parameters (setScanningFreq() class function)
Increase sequentially the frequency of my device (increaseFreq() class function)
Reset and close the USB connection.
I can obtain this behavior when I use the dll functions directly into the _tmain() therefore the device works correctly, but when I wrap the dll functions into a class and try to use the class something goes wrong.
I repeat the above process (list item 1-5) several times: sometimes it works fine, sometimes the program stop and the debugger gives me this error:
First-chance exception at 0x77533fb7 in AOTFcontrollerDebug.exe: 0xC0150014: The activation context activation stack for the running thread of execution is corrupt.
The error seems random, sometimes I can conclude 80 times the scan without any problem, sometimes it gives me error right at the first scan.
I tried to search for that error but I was not able to find anything useful.
Anyone can help? I guess could be related on how the dll functions are called in my class?
Here is the main function code:
// AOTFcontrollerDebug.cpp : Defines the entry point for the console application.
//
#include "stdafx.h"
#include "AOTFcontrollerDebug.h"
#include "AOTF_Controller.h"
#include <iostream>
#include <string>
#include <sstream>
#include <AotfLibrary.h>
#define DEFAULT_STARTFREQUENCY 78
#define DEFAULT_ENDFREQUENCY 95.5
#define DEFAULT_NUMOFFRAMES 256
#ifdef _DEBUG
#define new DEBUG_NEW
#endif
// The one and only application object
CWinApp theApp;
using namespace std;
int _tmain(int argc, TCHAR* argv[], TCHAR* envp[])
{
int nRetCode = 0;
HMODULE hModule = ::GetModuleHandle(NULL);
if (hModule != NULL)
{
// initialize MFC and print and error on failure
if (!AfxWinInit(hModule, NULL, ::GetCommandLine(), 0))
{
// TODO: change error code to suit your needs
_tprintf(_T("Fatal Error: MFC initialization failed\n"));
nRetCode = 1;
}
else
{
// TODO: code your application's behavior here.
std::cout << "-----AOTF Controller Debugging-----"<<endl;
//input of scans to do
int repeatedScan;
std::cout << "Type how many repeated scan: "<<endl;
std::cin >> repeatedScan;
//instance
AOTF_Controller m_AOTF_Controller;
std::cout << "AOTF Controller instance done..."<<endl;
//loop over scans
for(int i =0;i<repeatedScan;i++)
{
m_AOTF_Controller.connect();
std::cout << "AOTF Controller connected..."<<endl;
std::cout << "Scan number : "<< (i + 1) <<endl;
m_AOTF_Controller.init();
//set the delta freq to increase at each step
m_AOTF_Controller.setScanningFreq(DEFAULT_STARTFREQUENCY, DEFAULT_ENDFREQUENCY, DEFAULT_NUMOFFRAMES);
//loop over wavelengths
int sleep_ms = 4;
for (int j =0; j <DEFAULT_NUMOFFRAMES; j++)
{
Sleep(sleep_ms) ;
m_AOTF_Controller.increaseFreq();
//std::cout << " "<< (j + 1) ;
}
// terminate scans
m_AOTF_Controller.reset();
m_AOTF_Controller.disconnect();
std::cout << endl <<"Scan number "<< (i + 1) << "terminated successfully" <<endl;
Sleep(sleep_ms*100) ;
}
}
}
else
{
// TODO: change error code to suit your needs
_tprintf(_T("Fatal Error: GetModuleHandle failed\n"));
nRetCode = 1;
}
return nRetCode;
}
and here the Aotf_Controller class code:
//Aotf_Controller.h
#pragma once
#include <AotfLibrary.h>
#include <string>
#include <sstream>
#include <iomanip>
#define CONVERSION_MHZ_TO_HZ 1000000
class AOTF_Controller
{
private:
enum Error {SUCCESSFUL , CONNECTION_ERROR, DISCONNECTION_ERROR, INIT_ERROR, RESET_ERROR , SET_ERROR }; // error enum values
HANDLE hAotfController;
int currentGain;
long currentFreq; // current frequency in Hz
long startFreq, endFreq, deltaFreq; // frequency values for the scanning in Hz
public:
AOTF_Controller(void);
~AOTF_Controller(void);
AOTF_Controller::Error connect();
AOTF_Controller::Error disconnect();
AOTF_Controller::Error init();
AOTF_Controller::Error setFreq(float freq); // for frequency value in MHZ (precision to the 3rd decimal i.e. KHz)
AOTF_Controller::Error setFreq(long freq); // for frequency value in Hz
AOTF_Controller::Error setGain(int gain);
AOTF_Controller::Error reset();
AOTF_Controller::Error setScanningFreq(float _startFreq, float _endFreq, int numOfFrames);
AOTF_Controller::Error increaseFreq();
};
//Aotf_Controller.cpp
#include "StdAfx.h"
#include "AOTF_Controller.h"
AOTF_Controller::AOTF_Controller(void)
{
currentGain = 0;
currentFreq = 0;
startFreq = 0;
endFreq = 0;
deltaFreq = 0;
hAotfController = NULL;
}
AOTF_Controller::~AOTF_Controller(void)
{
}
AOTF_Controller::Error AOTF_Controller::connect()
{
int iInstance = 0;
hAotfController = AotfOpen(iInstance);
if (!hAotfController)
{
return CONNECTION_ERROR;
}
else
{
return SUCCESSFUL;
}
}
AOTF_Controller::Error AOTF_Controller::disconnect()
{
if (!AotfClose (hAotfController))
{
return DISCONNECTION_ERROR;
}
else
{
hAotfController = NULL;
return SUCCESSFUL;
}
}
AOTF_Controller::Error AOTF_Controller::init()
{
std::string ampCom="dds a 0 16383\r"; //Command to set the amplitude parameter to the max
std::string modCom="mod dac * 16383\r";//Command to set the dac parameter to the max
int gain = 255; // set the gain to the max
if (!AotfWrite(hAotfController, ampCom.length(), (char *)ampCom.c_str()))
{
return Error::INIT_ERROR;
}
if (!AotfWrite(hAotfController, modCom.length(), (char *)modCom.c_str()))
{
return INIT_ERROR;
}
setGain(gain);
return SUCCESSFUL;
}
AOTF_Controller::Error AOTF_Controller::reset()
{
std::string resetCom = "dds reset\r";
if(!AotfWrite(hAotfController, resetCom.length() , (char *)resetCom.c_str()))
{
return RESET_ERROR;
}
return SUCCESSFUL;
}
AOTF_Controller::Error AOTF_Controller::setFreq(float freq)
{
long freqHz = (long)freq*CONVERSION_MHZ_TO_HZ;
setFreq(freqHz);
return SUCCESSFUL;
}
AOTF_Controller::Error AOTF_Controller::setFreq(long freq)
{
std::ostringstream oss; //stream to build the string
//building the string for the Frequency
oss << "dds f 0 !" << std::fixed << std::setprecision(0) << freq << "\r";
std::string freqCom = oss.str();
//send command to the AOTF
if(!AotfWrite(hAotfController, freqCom.length(), (char *) freqCom.c_str())) // set the frequency (80-120)
{
return SET_ERROR;
}
currentFreq = freq; // update monitoring variable in HZ
return Error::SUCCESSFUL;
}
AOTF_Controller::Error AOTF_Controller::setGain(int gain)
{
std::ostringstream oss; //stream to build the string
//building the string for the Gain
oss << "dds gain -p* * " << gain << "\r";
std::string gainCom = oss.str();
//send command to the AOTF
if(!AotfWrite(hAotfController, gainCom.length(), (char * )gainCom.c_str())) // set the gain (0-255)
{
return SET_ERROR;
}
currentGain = gain;
return SUCCESSFUL;
}
AOTF_Controller::Error AOTF_Controller::setScanningFreq(float _startFreq, float _endFreq, int numOfFrames)
{
float FreqRange = (_endFreq - _startFreq); //calculate range
//calculate DeltaFrequency (frequency increase after each captured frame)
deltaFreq = (long) ((FreqRange/(float)(numOfFrames-1))*(float)CONVERSION_MHZ_TO_HZ); //conversion from MHz to Hz
startFreq = (long) (_startFreq*CONVERSION_MHZ_TO_HZ);
endFreq = (long) (_endFreq*CONVERSION_MHZ_TO_HZ);
setFreq(_startFreq);
return SUCCESSFUL;
}
AOTF_Controller::Error AOTF_Controller::increaseFreq()
{
if (deltaFreq ==0)
{
return SET_ERROR;
}
long newFreq = currentFreq + deltaFreq;
std::ostringstream oss;
oss << "dds f 0 !" << std::fixed << std::setprecision(0) << newFreq << "\r";
std::string freqCom = oss.str();
//send command to the AOTF
if(!AotfWrite(hAotfController, freqCom.length(), (char *)freqCom.c_str())) // set the frequency (80-120)value
{
return SET_ERROR;
}
currentFreq = newFreq;
return SUCCESSFUL;
}