Rcpp: Calling function with object as argument - c++11

I have a function in Rcpp, which creates a very long map-structure within a class. I've given a simple example of it below:
#include <Rcpp.h>
using namespace Rcpp;
class A{
private:
std::map<int, int> m_map;
public:
void fill_map(const size_t limit){
for(size_t i=0; i<limit; ++i){
m_map[i] = i;
}
}
size_t size_map(){return m_map.size();}
};
// [[Rcpp::export]]
void func1(const size_t limit) {
A a;
a.fill_map(limit);
}
/* NOT WORKING */
// [[Rcpp::export]]
void func2(A a)
{
std::cout << a.size_map() << "\n";
}
/* NOT WORKING */
Say I call func1(1e7), which fills up the map in the a-object. I need to pass this A-object to other functions as shown above with func2.
However, my example with func2 doesn't work. Within the Rcpp-framework, what is the correct and most efficient approach to call func2 with an object defined in a previous function?

C++ code
#include <Rcpp.h>
using namespace Rcpp;
class A
{
private:
std::map<int, int> m_map;
public:
void fill_map(const size_t limit)
{
for(size_t i=0; i<limit; ++i)
{
m_map[i] = i;
}
}
size_t size_map(){return m_map.size();}
};
// [[Rcpp::export]]
XPtr<A> func1(const size_t limit)
{
XPtr<A> ptr(new A(), true);
ptr->fill_map(limit);
return(ptr);
}
// [[Rcpp::export]]
void func2(XPtr<A> ptr)
{
Rcout << ptr->size_map() << std::endl;
}
R code
a = func1(10)
func2(a)
a being an External pointer.

Related

Custom compare class not working as I expect for pointers to a user defined class in a std::set container

I can't figure out why in this code example the std::set container is not ordering the Entities as I expect on the basis of the compare class I defined. Anyone can help me please? Thanks
#include <iostream>
#include <set>
class Entity {
public:
int num;
Entity(int num):num(num){}
bool operator< (const Entity& _entity) const { return (this->num < _entity.num); }
};
struct my_cmp {
bool operator() (const Entity* lhs, const Entity* rhs) const { return (lhs < rhs); }
};
class EntityManager {
private:
std::set<Entity*, my_cmp> entities;
public:
void AddEntity(int num) { entities.insert(new Entity(num)); }
void ListAllEntities() const {
unsigned int i = 0;
for (auto& entity: entities) {
std::cout << "Entity[" << i << "]: num:" << entity->num << std::endl;
i++;
}
}
};
int main(void) {
EntityManager manager;
manager.AddEntity(2);
manager.AddEntity(1);
manager.AddEntity(4);
manager.AddEntity(3);
manager.ListAllEntities();
return 0;
}
Output:
Entity[0]: num:2
Entity[1]: num:1
Entity[2]: num:4
Entity[3]: num:3
I would expect the following output instead:
Entity[1]: num:1
Entity[0]: num:2
Entity[3]: num:3
Entity[2]: num:4
You need to dereference your pointers *lhs < *rhs. You're just comparing the value of the pointers currently, so your order is dependent on their location in memory.
#include <iostream>
#include <set>
class Entity {
public:
int num;
Entity(int num):num(num){}
bool operator< (const Entity& _entity) const { return (this->num < _entity.num); }
};
struct my_cmp {
bool operator() (const Entity* lhs, const Entity* rhs) const { return (*lhs < *rhs); }
};
class EntityManager {
private:
std::set<Entity*, my_cmp> entities;
public:
void AddEntity(int num) { entities.insert(new Entity(num)); }
void ListAllEntities() const {
unsigned int i = 0;
for (auto& entity: entities) {
std::cout << "Entity[" << i << "]: num:" << entity->num << std::endl;
i++;
}
}
};
int main(void) {
EntityManager manager;
manager.AddEntity(2);
manager.AddEntity(1);
manager.AddEntity(4);
manager.AddEntity(3);
manager.ListAllEntities();
return 0;
}
Demo

Why a member function in a class template creates the same object in the same address

I am working on testing a lock-free work-stealing queue I wrote recently. However, I found a weird issue, that when I push a new item to the queue, it only returns me the same object that was pushed at the last. It took me one day and I still cannot figure out why this happened.
This is the output, every time, the data is the same to be pushed to the queue, which is why I only have the last result being 45, it should be all 45 for the 4 res items. Anybody can help me here :(
push_back addr: 0x21d3ea0 bk: 0 &data: 0x7ffe36802380
push_back addr: 0x21d3ea4 bk: 0 &data: 0x7ffe36802380
push_back addr: 0x21d3ea8 bk: 0 &data: 0x7ffe36802380
push_back addr: 0x21d3eac bk: 0 &data: 0x7ffe36802380
res[0]=-1
res[1]=-1
res[2]=-1
res[3]=45
Below is the simplified code:
#include <memory>
#include <functional>
#include <type_traits>
class FunctionWrapper {
private:
class ImplInterface {
public:
virtual void invoke() = 0;
virtual ~ImplInterface() {}
};
std::unique_ptr<ImplInterface> impl;
template <typename F, typename... Args>
class Impl : public ImplInterface {
private:
std::function<void()> callBack;
public:
Impl(F&& f_, Args&&... args_) {
callBack = [&f_, &args_...]() { f_(std::forward<Args>(args_)...); };
}
void invoke() override { callBack(); }
};
public:
template <typename F, typename... Args>
FunctionWrapper(F&& f_, Args&&... args_) : impl(new Impl<F, Args...>(std::forward<F>(f_), std::forward<Args>(args_)...)) {}
void operator()() { impl->invoke(); }
FunctionWrapper() = default;
FunctionWrapper(FunctionWrapper&& other) : impl(std::move(other.impl)) {}
FunctionWrapper& operator=(FunctionWrapper&& other) {
impl = std::move(other.impl);
return *this;
}
FunctionWrapper(const FunctionWrapper&) = delete;
FunctionWrapper(FunctionWrapper&) = delete;
FunctionWrapper& operator=(const FunctionWrapper&) = delete;
};
#include <atomic>
#include <array>
#include <iostream>
#include "functionwrapper.h"
class LockFreeWorkStealingQueue {
private:
using DataType = FunctionWrapper;
static constexpr auto DEFAULT_COUNT = 2048u;
static constexpr auto MASK = DEFAULT_COUNT - 1u;
std::array<DataType, DEFAULT_COUNT> q;
unsigned int ft{0};
unsigned int bk{0};
public:
LockFreeWorkStealingQueue() {}
LockFreeWorkStealingQueue(const LockFreeWorkStealingQueue&) = delete;
LockFreeWorkStealingQueue& operator=(const LockFreeWorkStealingQueue&) = delete;
void push_back(DataType data) {
std::cout << "bk: " << (bk&MASK) << " &data: " << &data << std::endl;
q[bk & MASK] = std::move(data);
bk++;
}
bool try_pop_back(DataType& res) {
if (bk > ft) {
res = std::move(q[(bk - 1) & MASK]);
bk--;
return true;
}
return false;
}
};
#include "lockfreeworkstealingqueue.h"
#include <iostream>
#include <algorithm>
#include <numeric>
#include <cassert>
#include <vector>
constexpr unsigned int NUM = 4;
void sumOver(const std::vector<int>& v, int& res) {
res = std::accumulate(v.begin(), v.end(), 0);
//std::cout << "call sumOver, res = " << res << std::endl;
//std::cout << "call sumOver, addr: " << &res << std::endl;
}
int main () {
std::vector<int> v { 1,2,3,4,5,6,7,8,9 };
std::vector<int> res(NUM, -1);
std::vector<LockFreeWorkStealingQueue> wsq(4);
{
for (auto i = 0; i < 4; ++i) {
for (auto j = 0; j < NUM / 4; ++j) {
std::cout << "push_back addr: " << &res[i*(NUM/4)+j] << std::endl;
wsq[i].push_back(FunctionWrapper(sumOver, std::ref(v), std::ref(res.at(i*(NUM/4)+j))));
}
}
FunctionWrapper f;
for (auto i = 0; i < 4; ++i) {
for (auto j = 0; j < NUM / 4; ++j) {
if(wsq[i].try_pop_back(f)) {
f();
}
}
}
}
for (auto i = 0; i < 4; ++i) {
for (auto j = 0; j < NUM / 4; ++j) {
std::cout << "res[" << i*(NUM/4)+j << "]=" << res[i*(NUM/4)+j] << std::endl;
}
}
return 0;
}
EDIT: I made a change to functionwrapper.h to refect on the comments. and now it works well.
#include <memory>
#include <functional>
class FunctionWrapper {
private:
std::function<void()> callback;
public:
template <typename F, typename... Args>
FunctionWrapper(F&& f_, Args&&... args_) : callback([f_, args_...]() { f_(args_...); }) {}
void operator()() { callback(); }
FunctionWrapper() = default;
FunctionWrapper(FunctionWrapper&& other) : callback(std::move(other.callback)) {}
FunctionWrapper& operator=(FunctionWrapper&& other) {
callback = std::move(other.callback);
return *this;
}
FunctionWrapper(const FunctionWrapper&) = delete;
FunctionWrapper(FunctionWrapper&) = delete;
FunctionWrapper& operator=(const FunctionWrapper&) = delete;
};
The lambda in FunctionWrapper::Impl captures references to temporary std::reference_wrapper instances (produced by std::ref calls in main). By the time the lambda is actually called, those temporaries have long been destroyed and the references are dangling. Whereupon your program exhibits undefined behavior, by way of accessing objects whose lifetime has ended.
You want to capture by value instead, as in
Impl(F&& f_, Args&&... args_) {
callBack = [f_, args_...]() { f_(args_...); };
}
Demo

Error in storing outer class object in inner class C++

I was implementing the ring buffer and have encountered an error. What does it mean to store a reference of outer class(class ring) object(m_ring) in inner class(class iterator) and when I remove the reference(&) the program compiles correctly but crashes. Please explain what is happening.(See the comment in Ring.h) Sorry for bad English.
// Ring.h
#ifndef RING.H
#define RING.H
#include <iostream>
using namespace std;
template<class T>
class ring {
unsigned int m_size;
int m_pos;
T *m_values;
public:
class iterator;
public:
ring(unsigned int size) : m_size(size), m_pos(0)
{
m_values = new T[m_size];
}
~ring()
{
delete[] m_values;
}
void add(const T &val)
{
m_values[m_pos] = val;
m_pos++;
m_pos %= m_size;
}
T& get(int pos)
{
return m_values[pos];
}
iterator begin()
{
return iterator(0, *this);
}
iterator end()
{
return iterator(m_size, *this);
}
};
template<class T>
class ring<T>::iterator {
int m_pos;
ring &m_ring; // Removing & gives garbage output.
public:
iterator(int pos, ring& aRing) : m_pos(pos), m_ring(aRing){}
bool operator!=(const iterator &other) const
{
return other.m_pos != m_pos;
}
iterator &operator++(int)
{
m_pos++;
return *this;
}
iterator &operator++()
{
m_pos++;
return *this;
}
T &operator*()
{
// return m_ring.m_values[m_pos];
return m_ring.get(m_pos);
}
};
#endif // RING
Driver program :
// Ring_Buffer_Class.cpp
#include <iostream>
#include "ring.h"
using namespace std;
int main()
{
ring<string> textring(3);
textring.add("one");
textring.add("two");
textring.add("three");
textring.add("four");
// C++ 98
for(ring<string>::iterator it = textring.begin(); it != textring.end(); it++)
{
cout << *it << endl;
}
cout << endl;
// C++11
for(string value : textring)
{
cout << value << endl;
}
return 0;
}
I also observed that removing ~ring() (Destructor) results into correct output.
Expected output :
four
two
three
four
two
three

Pass f(a) and f(a,b) as same slot of template parameter : without require explicit signature passing

I want to pass two functions with different signature into a same slot of class template parameter (one each time).
Ignore the strict syntax, this is what I want :-
void hf1 (int a) { std::cout<< "hf1" <<std::endl; }
void hf2 (int a, int i){ std::cout<< "hf2 "<<i<<std::endl; }
template<hfX> class Collection{
int i_=56;
public: test(){
if( "hfX has 1 param" ){hfX(0);} //call hf1
else {hfX(0,i_);} //call hf2
}
};
int main(){
Collection<&hf1> test1; test1.test(); // print "hf1"
Collection<&hf2> test2; test2.test(); // print "hf2 56"
}
Here is the code that works OK, but its usage is not so convenient :-
template<typename ... AA> using hfX = void(*)(AA ... );
void hf1 (int a) { std::cout<< "hf1" <<std::endl; }
void hf2 (int a, int i) { std::cout<< "hf2 "<<i <<std::endl; }
template <typename Tf, Tf F>
class Collection;
template <typename ... I, hfX<I...> F>
class Collection<hfX<I...>, F>{
public:
int i_=56;
template <std::size_t N = sizeof...(I)>
typename std::enable_if<N == 1U, void>::type test (){
F(0);
}
template <std::size_t N = sizeof...(I)>
typename std::enable_if<N == 2U, void>::type test (){
F(0,i_);
}
};
The usage:-
int main () {
Collection<hfX<int>, hf1> test1; //<--- #A dirty signature
Collection<hfX<int,int>, hf2> test2; //<--- #B dirty signature
test1.test(); // print "hf1"
test2.test(); // print "hf2 56"
}
Live version : https://ideone.com/f20BEk
Question
It would be nice if I can call it without explicit redundant signature.
Collection<hf1> test1; //or &hf
Collection<hf2> test2;
How to improve code (especially around hfX and Collection) to make its usage easier?
I don't know how to make what do you want with functions.
But if you can, instead of functions, accept to use static method in classes or structs (and pass that classes/structs as template argument)...
#include <iostream>
struct sf1
{ static void hf (int a) { std::cout << "hf1" << std::endl; } };
struct sf2
{ static void hf (int a, int i) { std::cout << "hf2 " << i << std::endl; } };
template <typename S>
class Collection
{
private:
int i_ = 56;
public:
template <typename T = S>
decltype(T::hf(0)) test() { S::hf(0); /*call sf1::hf */ }
template <typename T = S>
decltype(T::hf(0, 0)) test() { S::hf(0,i_); /*call sf2::hf */ }
};
int main ()
{
Collection<sf1> test1; test1.test(); // print "hf1"
Collection<sf2> test2; test2.test(); // print "hf2 56"
}

I'm trying to implement GPS data into the waveshortmessage, but i'm having problems implementing omnet2traci function

I'm using omnet5, veins 4.4, and sumo 0.25. I've looked at Converting Veins Coordinates to GPS which didn't help much since i have the updated version.
This one https://stackoverflow.com/questions/40650825/connection-to-traci-server-lost-check-your-servers-log-error-message-88-soc seems like it might work with a little error checking, but I'm not sure what the user did to make it work.
I've seen that you can use omnet2traci to convert the regular coordinates to the sumo ones, but I'm having trouble implementing it properly. When I tried calling it in message with:
class Veins::TraCIConnection::omnet2traci;
then using:
Veins::TraCICoord gpspos = omnet2traci(senderPos);
but I'm getting undeclared identifier error. I tried changing to .cc and .h code to compensate for it by creating a small copy of the omnet2traci coding from TraCIConnection. After all that it gives me errors:
omnetpp-5.0/include/omnetpp/cdynamicexpression.h:50:9: error: expected identifier
ADD, SUB, MUL, DIV, MOD, POW, NEG,
^
.\veins/modules/mobility/traci/TraCIConstants.h:707:13: note: expanded from macro 'ADD'
#define ADD 0x80
^
omnetpp-5.0/include/omnetpp/coutvector.h:66:27: error: expected identifier
enum Type { TYPE_INT, TYPE_DOUBLE, TYPE_ENUM };
^
.\veins/modules/mobility/traci/TraCIConstants.h:304:21: note: expanded from macro 'TYPE_DOUBLE'
#define TYPE_DOUBLE 0x0B
^
At this point it seems like it working around the problem and hoping it works instead of actually solving the problem. Full code below, added in parts are starred. *note I had to snip the end parts of the .cc code because it went over the text limit, but nothing was changed.
Waveshortmessage.msg
//Waveshortmessage.msg
cplusplus {{
**#include <stdint.h>
#include "veins/modules/mobility/traci/TraCIBuffer.h"
#include "veins/modules/mobility/traci/TraCICommandInterface.h"
#include "veins/modules/mobility/traci/TraCIConnection.h"
#include "veins/modules/mobility/traci/TraCIConstants.h"
#include "veins/modules/mobility/traci/TraCICoord.h"**
#include "veins/base/utils/Coord.h"
}}
class noncobject Coord;
**class noncobject Veins::TraCICoord;
class Veins::TraCIConnection::omnet2traci;**
packet WaveShortMessage {
//Version of the Wave Short Message
int wsmVersion = 0;
//Determine which security mechanism was used
int securityType = 0;
//Channel Number on which this packet was sent
int channelNumber;
//Data rate with which this packet was sent
int dataRate = 1;
//Power Level with which this packet was sent
int priority = 3;
//Unique number to identify the service
int psid = 0;
//Provider Service Context
string psc = "Service with some Data";
//Length of Wave Short Message
int wsmLength;
//Data of Wave Short Message
string wsmData = "Some Data";
int senderAddress = 0;
int recipientAddress = -1;
int serial = 0;
Coord senderPos;
**Veins::TraCICoord gpspos = omnet2traci(senderPos);**
simtime_t timestamp = 0;
}
Waveshortmessage.cc
//waveshortmessage.cc
// Generated file, do not edit! Created by nedtool 5.0 from veins/modules/messages/WaveShortMessage.msg.
//
**#define WANT_WINSOCK2
#include <platdep/sockets.h>
#if defined(_WIN32) || defined(__WIN32__) || defined(WIN32) || defined(__CYGWIN__) || defined(_WIN64)
#include <ws2tcpip.h>
#else
#include <netinet/tcp.h>
#include <netdb.h>
#include <arpa/inet.h>
#endif
#include <algorithm>
#include <functional>
//#include "veins/modules/mobility/traci/TraCIConnection.h"
#include "veins/modules/mobility/traci/TraCIConstants.h"
#define MYDEBUG EV**
// Disable warnings about unused variables, empty switch stmts, etc:
#ifdef _MSC_VER
# pragma warning(disable:4101)
# pragma warning(disable:4065)
#endif
#include <iostream>
#include <sstream>
#include "WaveShortMessage_m.h"
namespace omnetpp {
// Template pack/unpack rules. They are declared *after* a1l type-specific pack functions for multiple reasons.
// They are in the omnetpp namespace, to allow them to be found by argument-dependent lookup via the cCommBuffer argument
// Packing/unpacking an std::vector
template<typename T, typename A>
void doParsimPacking(omnetpp::cCommBuffer *buffer, const std::vector<T,A>& v)
{
int n = v.size();
doParsimPacking(buffer, n);
for (int i = 0; i < n; i++)
doParsimPacking(buffer, v[i]);
}
template<typename T, typename A>
void doParsimUnpacking(omnetpp::cCommBuffer *buffer, std::vector<T,A>& v)
{
int n;
doParsimUnpacking(buffer, n);
v.resize(n);
for (int i = 0; i < n; i++)
doParsimUnpacking(buffer, v[i]);
}
// Packing/unpacking an std::list
template<typename T, typename A>
void doParsimPacking(omnetpp::cCommBuffer *buffer, const std::list<T,A>& l)
{
doParsimPacking(buffer, (int)l.size());
for (typename std::list<T,A>::const_iterator it = l.begin(); it != l.end(); ++it)
doParsimPacking(buffer, (T&)*it);
}
template<typename T, typename A>
void doParsimUnpacking(omnetpp::cCommBuffer *buffer, std::list<T,A>& l)
{
int n;
doParsimUnpacking(buffer, n);
for (int i=0; i<n; i++) {
l.push_back(T());
doParsimUnpacking(buffer, l.back());
}
}
// Packing/unpacking an std::set
template<typename T, typename Tr, typename A>
void doParsimPacking(omnetpp::cCommBuffer *buffer, const std::set<T,Tr,A>& s)
{
doParsimPacking(buffer, (int)s.size());
for (typename std::set<T,Tr,A>::const_iterator it = s.begin(); it != s.end(); ++it)
doParsimPacking(buffer, *it);
}
template<typename T, typename Tr, typename A>
void doParsimUnpacking(omnetpp::cCommBuffer *buffer, std::set<T,Tr,A>& s)
{
int n;
doParsimUnpacking(buffer, n);
for (int i=0; i<n; i++) {
T x;
doParsimUnpacking(buffer, x);
s.insert(x);
}
}
// Packing/unpacking an std::map
template<typename K, typename V, typename Tr, typename A>
void doParsimPacking(omnetpp::cCommBuffer *buffer, const std::map<K,V,Tr,A>& m)
{
doParsimPacking(buffer, (int)m.size());
for (typename std::map<K,V,Tr,A>::const_iterator it = m.begin(); it != m.end(); ++it) {
doParsimPacking(buffer, it->first);
doParsimPacking(buffer, it->second);
}
}
template<typename K, typename V, typename Tr, typename A>
void doParsimUnpacking(omnetpp::cCommBuffer *buffer, std::map<K,V,Tr,A>& m)
{
int n;
doParsimUnpacking(buffer, n);
for (int i=0; i<n; i++) {
K k; V v;
doParsimUnpacking(buffer, k);
doParsimUnpacking(buffer, v);
m[k] = v;
}
}
// Default pack/unpack function for arrays
template<typename T>
void doParsimArrayPacking(omnetpp::cCommBuffer *b, const T *t, int n)
{
for (int i = 0; i < n; i++)
doParsimPacking(b, t[i]);
}
template<typename T>
void doParsimArrayUnpacking(omnetpp::cCommBuffer *b, T *t, int n)
{
for (int i = 0; i < n; i++)
doParsimUnpacking(b, t[i]);
}
// Default rule to prevent compiler from choosing base class' doParsimPacking() function
template<typename T>
void doParsimPacking(omnetpp::cCommBuffer *, const T& t)
{
throw omnetpp::cRuntimeError("Parsim error: no doParsimPacking() function for type %s", omnetpp::opp_typename(typeid(t)));
}
template<typename T>
void doParsimUnpacking(omnetpp::cCommBuffer *, T& t)
{
throw omnetpp::cRuntimeError("Parsim error: no doParsimUnpacking() function for type %s", omnetpp::opp_typename(typeid(t)));
}
} // namespace omnetpp
// forward
template<typename T, typename A>
std::ostream& operator<<(std::ostream& out, const std::vector<T,A>& vec);
// Template rule which fires if a struct or class doesn't have operator<<
template<typename T>
inline std::ostream& operator<<(std::ostream& out,const T&) {return out;}
// operator<< for std::vector<T>
template<typename T, typename A>
inline std::ostream& operator<<(std::ostream& out, const std::vector<T,A>& vec)
{
out.put('{');
for(typename std::vector<T,A>::const_iterator it = vec.begin(); it != vec.end(); ++it)
{
if (it != vec.begin()) {
out.put(','); out.put(' ');
}
out << *it;
}
out.put('}');
char buf[32];
sprintf(buf, " (size=%u)", (unsigned int)vec.size());
out.write(buf, strlen(buf));
return out;
}
**Veins::TraCICoord Veins::TraCIConnection::omnet2traci(Coord coord) const {
return TraCICoord(coord.x + netbounds1.x - margin, (netbounds2.y - netbounds1.y) - (coord.y - netbounds1.y) + margin);
}
std::list<Veins::TraCICoord> Veins::TraCIConnection::omnet2traci(const std::list<Coord>& list) const {
std::list<TraCICoord> result;
std::transform(list.begin(), list.end(), std::back_inserter(result), std::bind1st(std::mem_fun<TraCICoord, TraCIConnection, Coord>(&TraCIConnection::omnet2traci), this));
return result;
}**
Register_Class(WaveShortMessage);
WaveShortMessage::WaveShortMessage(const char *name, int kind) : ::omnetpp::cPacket(name,kind)
{
this->wsmVersion = 0;
this->securityType = 0;
this->channelNumber = 0;
this->dataRate = 1;
this->priority = 3;
this->psid = 0;
this->psc = "Service with some Data";
this->wsmLength = 0;
this->wsmData = "Some Data";
this->senderAddress = 0;
this->recipientAddress = -1;
this->serial = 0;
this->gpspos = omnet2traci(senderPos);
this->timestamp = 0;
}
WaveShortMessage::WaveShortMessage(const WaveShortMessage& other) : ::omnetpp::cPacket(other)
{
copy(other);
}
WaveShortMessage::~WaveShortMessage()
{
}
WaveShortMessage& WaveShortMessage::operator=(const WaveShortMessage& other)
{
if (this==&other) return *this;
::omnetpp::cPacket::operator=(other);
copy(other);
return *this;
}
void WaveShortMessage::copy(const WaveShortMessage& other)
{
this->wsmVersion = other.wsmVersion;
this->securityType = other.securityType;
this->channelNumber = other.channelNumber;
this->dataRate = other.dataRate;
this->priority = other.priority;
this->psid = other.psid;
this->psc = other.psc;
this->wsmLength = other.wsmLength;
this->wsmData = other.wsmData;
this->senderAddress = other.senderAddress;
this->recipientAddress = other.recipientAddress;
this->serial = other.serial;
this->senderPos = other.senderPos;
this->gpspos = other.gpspos;
this->timestamp = other.timestamp;
}
void WaveShortMessage::parsimPack(omnetpp::cCommBuffer *b) const
{
::omnetpp::cPacket::parsimPack(b);
doParsimPacking(b,this->wsmVersion);
doParsimPacking(b,this->securityType);
doParsimPacking(b,this->channelNumber);
doParsimPacking(b,this->dataRate);
doParsimPacking(b,this->priority);
doParsimPacking(b,this->psid);
doParsimPacking(b,this->psc);
doParsimPacking(b,this->wsmLength);
doParsimPacking(b,this->wsmData);
doParsimPacking(b,this->senderAddress);
doParsimPacking(b,this->recipientAddress);
doParsimPacking(b,this->serial);
doParsimPacking(b,this->senderPos);
doParsimPacking(b,this->gpspos);
doParsimPacking(b,this->timestamp);
}
void WaveShortMessage::parsimUnpack(omnetpp::cCommBuffer *b)
{
::omnetpp::cPacket::parsimUnpack(b);
doParsimUnpacking(b,this->wsmVersion);
doParsimUnpacking(b,this->securityType);
doParsimUnpacking(b,this->channelNumber);
doParsimUnpacking(b,this->dataRate);
doParsimUnpacking(b,this->priority);
doParsimUnpacking(b,this->psid);
doParsimUnpacking(b,this->psc);
doParsimUnpacking(b,this->wsmLength);
doParsimUnpacking(b,this->wsmData);
doParsimUnpacking(b,this->senderAddress);
doParsimUnpacking(b,this->recipientAddress);
doParsimUnpacking(b,this->serial);
doParsimUnpacking(b,this->senderPos);
doParsimUnpacking(b,this->gpspos);
doParsimUnpacking(b,this->timestamp);
}
int WaveShortMessage::getWsmVersion() const
{
return this->wsmVersion;
}
void WaveShortMessage::setWsmVersion(int wsmVersion)
{
this->wsmVersion = wsmVersion;
}
int WaveShortMessage::getSecurityType() const
{
return this->securityType;
}
void WaveShortMessage::setSecurityType(int securityType)
{
this->securityType = securityType;
}
int WaveShortMessage::getChannelNumber() const
{
return this->channelNumber;
}
void WaveShortMessage::setChannelNumber(int channelNumber)
{
this->channelNumber = channelNumber;
}
int WaveShortMessage::getDataRate() const
{
return this->dataRate;
}
void WaveShortMessage::setDataRate(int dataRate)
{
this->dataRate = dataRate;
}
int WaveShortMessage::getPriority() const
{
return this->priority;
}
void WaveShortMessage::setPriority(int priority)
{
this->priority = priority;
}
int WaveShortMessage::getPsid() const
{
return this->psid;
}
void WaveShortMessage::setPsid(int psid)
{
this->psid = psid;
}
const char * WaveShortMessage::getPsc() const
{
return this->psc.c_str();
}
void WaveShortMessage::setPsc(const char * psc)
{
this->psc = psc;
}
int WaveShortMessage::getWsmLength() const
{
return this->wsmLength;
}
void WaveShortMessage::setWsmLength(int wsmLength)
{
this->wsmLength = wsmLength;
}
const char * WaveShortMessage::getWsmData() const
{
return this->wsmData.c_str();
}
void WaveShortMessage::setWsmData(const char * wsmData)
{
this->wsmData = wsmData;
}
int WaveShortMessage::getSenderAddress() const
{
return this->senderAddress;
}
void WaveShortMessage::setSenderAddress(int senderAddress)
{
this->senderAddress = senderAddress;
}
int WaveShortMessage::getRecipientAddress() const
{
return this->recipientAddress;
}
void WaveShortMessage::setRecipientAddress(int recipientAddress)
{
this->recipientAddress = recipientAddress;
}
int WaveShortMessage::getSerial() const
{
return this->serial;
}
void WaveShortMessage::setSerial(int serial)
{
this->serial = serial;
}
Coord& WaveShortMessage::getSenderPos()
{
return this->senderPos;
}
void WaveShortMessage::setSenderPos(const Coord& senderPos)
{
this->senderPos = senderPos;
}
Veins::TraCICoord& WaveShortMessage::getGpspos()
{
return this->gpspos;
}
void WaveShortMessage::setGpspos(const Veins::TraCICoord& gpspos)
{
this->gpspos = gpspos;
}
::omnetpp::simtime_t WaveShortMessage::getTimestamp() const
{
return this->timestamp;
}
void WaveShortMessage::setTimestamp(::omnetpp::simtime_t timestamp)
{
this->timestamp = timestamp;
}
class WaveShortMessageDescriptor : public omnetpp::cClassDescriptor
{
private:
mutable const char **propertynames;
public:
WaveShortMessageDescriptor();
virtual ~WaveShortMessageDescriptor();
virtual bool doesSupport(omnetpp::cObject *obj) const override;
virtual const char **getPropertyNames() const override;
virtual const char *getProperty(const char *propertyname) const override;
virtual int getFieldCount() const override;
virtual const char *getFieldName(int field) const override;
virtual int findField(const char *fieldName) const override;
virtual unsigned int getFieldTypeFlags(int field) const override;
virtual const char *getFieldTypeString(int field) const override;
virtual const char **getFieldPropertyNames(int field) const override;
virtual const char *getFieldProperty(int field, const char *propertyname) const override;
virtual int getFieldArraySize(void *object, int field) const override;
virtual std::string getFieldValueAsString(void *object, int field, int i) const override;
virtual bool setFieldValueAsString(void *object, int field, int i, const char *value) const override;
virtual const char *getFieldStructName(int field) const override;
virtual void *getFieldStructValuePointer(void *object, int field, int i) const override;
};
Register_ClassDescriptor(WaveShortMessageDescriptor);
WaveShortMessageDescriptor::WaveShortMessageDescriptor() : omnetpp::cClassDescriptor("WaveShortMessage", "omnetpp::cPacket")
{
propertynames = nullptr;
}
WaveShortMessageDescriptor::~WaveShortMessageDescriptor()
{
delete[] propertynames;
}
bool WaveShortMessageDescriptor::doesSupport(omnetpp::cObject *obj) const
{
return dynamic_cast<WaveShortMessage *>(obj)!=nullptr;
}
const char **WaveShortMessageDescriptor::getPropertyNames() const
{
if (!propertynames) {
static const char *names[] = { nullptr };
omnetpp::cClassDescriptor *basedesc = getBaseClassDescriptor();
const char **basenames = basedesc ? basedesc->getPropertyNames() : nullptr;
propertynames = mergeLists(basenames, names);
}
return propertynames;
}
const char *WaveShortMessageDescriptor::getProperty(const char *propertyname) const
{
omnetpp::cClassDescriptor *basedesc = getBaseClassDescriptor();
return basedesc ? basedesc->getProperty(propertyname) : nullptr;
}
int WaveShortMessageDescriptor::getFieldCount() const
{
omnetpp::cClassDescriptor *basedesc = getBaseClassDescriptor();
return basedesc ? 15+basedesc->getFieldCount() : 15;
}
unsigned int WaveShortMessageDescriptor::getFieldTypeFlags(int field) const
{
omnetpp::cClassDescriptor *basedesc = getBaseClassDescriptor();
if (basedesc) {
if (field < basedesc->getFieldCount())
return basedesc->getFieldTypeFlags(field);
field -= basedesc->getFieldCount();
}
static unsigned int fieldTypeFlags[] = {
FD_ISEDITABLE,
FD_ISEDITABLE,
FD_ISEDITABLE,
FD_ISEDITABLE,
FD_ISEDITABLE,
FD_ISEDITABLE,
FD_ISEDITABLE,
FD_ISEDITABLE,
FD_ISEDITABLE,
FD_ISEDITABLE,
FD_ISEDITABLE,
FD_ISEDITABLE,
FD_ISCOMPOUND,
FD_ISCOMPOUND,
FD_ISEDITABLE,
};
return (field>=0 && field<15) ? fieldTypeFlags[field] : 0;
}
const char *WaveShortMessageDescriptor::getFieldName(int field) const
{
omnetpp::cClassDescriptor *basedesc = getBaseClassDescriptor();
if (basedesc) {
if (field < basedesc->getFieldCount())
return basedesc->getFieldName(field);
field -= basedesc->getFieldCount();
}
static const char *fieldNames[] = {
"wsmVersion",
"securityType",
"channelNumber",
"dataRate",
"priority",
"psid",
"psc",
"wsmLength",
"wsmData",
"senderAddress",
"recipientAddress",
"serial",
"senderPos",
"gpspos",
"timestamp",
};
return (field>=0 && field<15) ? fieldNames[field] : nullptr;
}
Waveshortmessage.h
//Waveshortmessage.h
// Generated file, do not edit! Created by nedtool 5.0 from veins/modules/messages/WaveShortMessage.msg.
//
#ifndef __WAVESHORTMESSAGE_M_H
#define __WAVESHORTMESSAGE_M_H
#include <omnetpp.h>
// nedtool version check
#define MSGC_VERSION 0x0500
#if (MSGC_VERSION!=OMNETPP_VERSION)
# error Version mismatch! Probably this file was generated by an earlier version of nedtool: 'make clean' should help.
#endif
// cplusplus {{
** #include <stdint.h>
#include "veins/modules/mobility/traci/TraCIBuffer.h"
#include "veins/modules/mobility/traci/TraCICommandInterface.h"
#include "veins/modules/mobility/traci/TraCIConnection.h"
#include "veins/modules/mobility/traci/TraCIConstants.h"
#include "veins/modules/mobility/traci/TraCICoord.h" **
#include "veins/base/utils/Coord.h"
// }}
/**
* Class generated from <tt>veins/modules/messages/WaveShortMessage.msg:40</tt> by nedtool.
* <pre>
* packet WaveShortMessage
* {
* //Version of the Wave Short Message
* int wsmVersion = 0;
* //Determine which security mechanism was used
* int securityType = 0;
* //Channel Number on which this packet was sent
* int channelNumber;
* //Data rate with which this packet was sent
* int dataRate = 1;
* //Power Level with which this packet was sent
* int priority = 3;
* //Unique number to identify the service
* int psid = 0;
* //Provider Service Context
* string psc = "Service with some Data";
* //Length of Wave Short Message
* int wsmLength;
* //Data of Wave Short Message
* string wsmData = "Some Data";
*
* int senderAddress = 0;
* int recipientAddress = -1;
* int serial = 0;
* Coord senderPos;
*
* Veins::TraCICoord gpspos = omnet2traci(senderPos);
*
* simtime_t timestamp = 0;
*
* }
* </pre>
*/
class WaveShortMessage : public ::omnetpp::cPacket
{
protected:
int wsmVersion;
int securityType;
int channelNumber;
int dataRate;
int priority;
int psid;
::omnetpp::opp_string psc;
int wsmLength;
::omnetpp::opp_string wsmData;
int senderAddress;
int recipientAddress;
int serial;
Coord senderPos;
Veins::TraCICoord gpspos;
::omnetpp::simtime_t timestamp;
private:
void copy(const WaveShortMessage& other);
protected:
// protected and unimplemented operator==(), to prevent accidental usage
bool operator==(const WaveShortMessage&);
public:
WaveShortMessage(const char *name=nullptr, int kind=0);
WaveShortMessage(const WaveShortMessage& other);
virtual ~WaveShortMessage();
WaveShortMessage& operator=(const WaveShortMessage& other);
virtual WaveShortMessage *dup() const {return new WaveShortMessage(*this);}
virtual void parsimPack(omnetpp::cCommBuffer *b) const;
virtual void parsimUnpack(omnetpp::cCommBuffer *b);
// field getter/setter methods
virtual int getWsmVersion() const;
virtual void setWsmVersion(int wsmVersion);
virtual int getSecurityType() const;
virtual void setSecurityType(int securityType);
virtual int getChannelNumber() const;
virtual void setChannelNumber(int channelNumber);
virtual int getDataRate() const;
virtual void setDataRate(int dataRate);
virtual int getPriority() const;
virtual void setPriority(int priority);
virtual int getPsid() const;
virtual void setPsid(int psid);
virtual const char * getPsc() const;
virtual void setPsc(const char * psc);
virtual int getWsmLength() const;
virtual void setWsmLength(int wsmLength);
virtual const char * getWsmData() const;
virtual void setWsmData(const char * wsmData);
virtual int getSenderAddress() const;
virtual void setSenderAddress(int senderAddress);
virtual int getRecipientAddress() const;
virtual void setRecipientAddress(int recipientAddress);
virtual int getSerial() const;
virtual void setSerial(int serial);
virtual Coord& getSenderPos();
virtual const Coord& getSenderPos() const {return const_cast<WaveShortMessage*>(this)->getSenderPos();}
virtual void setSenderPos(const Coord& senderPos);
virtual Veins::TraCICoord& getGpspos();
virtual const Veins::TraCICoord& getGpspos() const {return const_cast<WaveShortMessage*>(this)->getGpspos();}
virtual void setGpspos(const Veins::TraCICoord& gpspos);
virtual ::omnetpp::simtime_t getTimestamp() const;
virtual void setTimestamp(::omnetpp::simtime_t timestamp);
**Coord traci2omnet(Veins::TraCICoord coord) const;
std::list<Coord> traci2omnet(const std::list<Veins::TraCICoord>&) const;
Veins::TraCICoord omnet2traci(Coord coord) const;
std::list<Veins::TraCICoord> omnet2traci(const std::list<Coord>&) const;**
};
inline void doParsimPacking(omnetpp::cCommBuffer *b, const WaveShortMessage& obj) {obj.parsimPack(b);}
inline void doParsimUnpacking(omnetpp::cCommBuffer *b, WaveShortMessage& obj) {obj.parsimUnpack(b);}
#endif // ifndef __WAVESHORTMESSAGE_M_H
Any help would be very appreciated. Thanks!
Currently I am working with localization in VANETs and I was facing the same problem.
As you can see in veins FAQ SUMO and OMNeT++ use different coordinate systems, so when you call mobility->getCurrentPosition() you get omnet coordinates not sumo coordinates.
I make some tests with proj4 C library and the values not was matching...
As me, probably you looking for the real sumo coordinates and for this you need call TraCIConnection::omnet2traci. But the problem is that not exists in veins a direct interface to access the object connection via TraCICommandInterface.
To overcome this trick I implemented one public method directly in the class TraCICommandInterface the signature of the method is the same of getLonLat method the diference is that inside I return the sumo coordinates calling the method `omnet2traci'. Now I can get the real sumo coordinates and use this for work with my real GPS dataset and one deadreckoning technique that I've implemented.
Follows the code of the method:
std::pair<double, double> TraCICommandInterface::getTraCIXY(const Coord& coord){
TraCICoord newCoord;
newCoord = connection.omnet2traci(coord);
return std::make_pair(newCoord.x, newCoord.y);
}
In your application class call this method using one TracICommandInterface object:
TraCIMobility* mobility;
TraCICommandInterface* traci;
Now in your initialize method instantiate this objects getting the active modules and traci interface:
mobility = TraCIMobilityAccess().get(getParentModule());
traci = mobility->getCommandInterface();
Now you will have this:
These are omnet++ cordinates:
Coord coordOmnet = mobility->getCurrentPosition();
These are sumo coordinates calling our implement method:
std::pair<double,double> coordTraCI = traci->getTraCIXY(mobility->getCurrentPosition());
Best Regards,
Pedro.
What is the main reason to convert the positions?
Why not use the OMNet/Veins - SUMO/TraCi coordinate?

Resources