error: invalid new-expression of abstract class type ‘gr::zeromq::base_sink_impl’ - constructor

namespace gr {
namespace zeromq {
class base_impl : public virtual gr::sync_block
{
public:
base_impl(int type, size_t itemsize, size_t vlen, int timeout, bool pass_tags);
virtual ~base_impl();
protected:
zmq::context_t *d_context;
zmq::socket_t *d_socket;
size_t d_vsize;
int d_timeout ;
bool d_pass_tags ;
};
class base_sink_impl : public base_impl
{
public:
base_sink_impl(int type, size_t itemsize, size_t vlen, char *address, int timeout, bool pass_tags, int hwm);
protected:
int send_message(const void *in_buf, const int in_nitems, const uint64_t in_offset);
};
} // namespace zeromq
}
`main(){
gr::zeromq::base_sink_impl *d_zeromq;
d_zeromq = new gr::zeromq::base_sink_impl(ZMQ_PUSH, sizeof(float), 1, "tcp://127.0.0.1:9098", 100, false, -1);
return 0;
}`
Hello!
After run this code, I have this error:
error: invalid new-expression of abstract class type ‘gr::zeromq::base_sink_impl’
_sink_impl(ZMQ_PUSH, sizeof(float), 1, "tcp://127.0.0.1:9098", 100, false, -1);
^
I'm not sure how to solve this error. I think I'm making wrong the constructor....
Please, any help will really appreciate it. Thanks

I find the error: the super class gr::sync_block has a virtual method called work.
I declared int work(int, gr_vector_const_void_star&, gr_vector_void_star&); inside the class base_impl and compiled.
Unfortunately, I can't run the project as It seems I have to configurate one of the CMakeList.txt to recognize zmq.hpp. It also seems I have to configurate the CMakeList.txt in my swig directory as I'm trying to do a GNURadio OOT Block using ZeroMQ.
Any help with it , I really Appreciate it.
Pd: If I resolve it, I 'll post it here:
GNU Radio OOT block : AttributeError: 'module' object has no attribute 'pthread' (using ZeroMQ sockets)

Related

How to get the underlying vector of an IVector<IInspectable>

I want to use a function that requires me to pass to it as a parameter a void pointer to beginning of a block of memory. The data has to be contiguous in memory for this function to work correctly.
Right now my data is stored in a IVector<IInspectable>. Looking at the memory layout of this IVector in the debugger I see that there is 28 bytes between my data. Which I think are the 7 function pointers from IUnknown and IInspectable. How can I get the underlying contiguous memory allocation of my data?
UPDATE:
Here is the solution I came up with.
Instead of using the IVector<IInspectable> I created a custom vector using the winrt::vector_base as recommended here: https://learn.microsoft.com/en-us/windows/uwp/cpp-and-winrt-apis/collections
and I wrapped it in a windows runtime component so that I can use this custom vector from C#.
It looks like this:
MyVector.idl
namespace RuntimeComponent1
{
[default_interface]
runtimeclass MyVector
{
MyVector();
void Append(IInspectable in_val);
}
}
MyVector.h
// MyVector.h
#pragma once
#include "MyVector.g.h"
namespace winrt::RuntimeComponent1::implementation
{
using namespace winrt::Windows::Foundation;
using namespace winrt::Windows::Foundation::Collections;
struct _MyVector :
implements<_MyVector, IVector<int>, IVectorView<int>, IIterable<int>>,
winrt::vector_base<_MyVector, int>
{
auto& get_container() const noexcept
{
return m_values;
}
auto& get_container() noexcept
{
return m_values;
}
private:
std::vector<int> m_values{};
};
struct MyVector : MyVectorT<MyVector, _MyVector>
{
MyVector() = default;
void Append(Windows::Foundation::IInspectable const& in_val);
};
}
namespace winrt::RuntimeComponent1::factory_implementation
{
struct MyVector : MyVectorT<MyVector, implementation::MyVector>
{
};
}
MyVector.cpp
#include "pch.h"
#include "MyVector.h"
using namespace winrt;
namespace winrt::RuntimeComponent1::implementation
{
void MyVector::Append(Windows::Foundation::IInspectable const& in_val)
{
base_type::Append(winrt::unbox_value<int>(in_val));
}
}
Example usage:
C#
MyRuntimeComponent.MyVector my_vec = new RuntimeComponent1.MyVector();
my_vec.Append(2);
my_vec.Append(4);
MyRuntimeComponent.MyControl my_control = new RuntimeComponent0.MyControl();
my_control.do_stuff_with_contiguous_memory(my_vec);
C++
void MyControl::do_stuff_with_contiguous_memory(RuntimeComponent1::MyVector const& in_data)
{
// Yay data is contiguous
auto contiguous_data = in_data.as<MyVector>()->get_container().data();
}
The end result is that I can pass data from C# to C++/WinRT and the data will be contiguous in C++, which fixes my original problem. It works but I wonder if there might be a simpler / better way?

How should memory be freed after an exception is thrown in C++?

I apologize if this question is a duplicate - I searched for a while, but it's possible that my Google-fu just isn't up to snuff.
I am modifying a C++ program that calls into a C library. The C library allocates a bunch of memory (using malloc()), and the C++ program uses it and then frees it. The catch is that the C++ program can throw an exception midway through execution, causing the allocated memory to never be freed.
As a (rather contrived) example:
/* old_library.c */
char *allocate_lots() {
char *mem = (char *)malloc(1024);
return mem;
}
/* my_prog.cpp */
void my_class::my_func () {
char *mem = allocate_lots();
bool problem = use(mem);
if (problem)
throw my_exception("Oh noes! This will be caught higher up");
free(mem); // Never gets called if problem is true
}
My question is: how ought I to deal with this? My first idea was to wrap the whole thing in a try/catch block, and in the catch just check and free the memory and re-throw the exception, but this seems graceless and clunky to me (and wouldn't work well if I want to actually catch an exception). Is there a better way to do it?
EDIT: I probably should have mentioned that we're using g++ 4.2.2, from back in 2007 before std::unique_ptr was introduced. Chalk it up to corporate inertia.
Use std::unique_ptr with a custom deleter that calls free:
class free_mem {
public:
void operator()(char *mem) { free(mem); }
};
void my_class::my_func() {
std::unique_ptr<char, free_mem> mem = allocate_lots();
You should make sure that you don't throw until after you have freed the memory - or that you use a suitable smart pointer structure to store the mem, such that when the throw happens, and the stack unwinds, the mem gets freed.
Wrap that rascal:
struct malloc_deleter {
template <typename T>
void operator () (T* p) const {
free(p);
}
};
void my_class::my_func () {
std::unique_ptr<char[],malloc_deleter> mem{allocate_lots()};
bool problem = use(mem.get());
if (problem)
throw my_exception("Oh noes! This will be caught higher up");
}
Since you're using an old compiler version that doesn't have unique_ptr, you can write your RAII wrapper yourself:
class ResourceWrapper {
public:
ResourceWrapper(char* ptr) : m_ptr(ptr) {}
~ResourceWrapper() { free(m_ptr); }
// whatever getters suit you, at the very least:
char* get() const { return m_ptr; }
private:
char* const m_ptr;
};
void my_class::my_func () {
ResourceWrapper mem(allocate_lots());
bool problem = use(mem.get());
if (problem)
throw my_exception("Oh noes! This will be caught higher up");
}
Just make sure not to allow copy/assignment even implicitly (which is why I made m_ptr const) or you'd risk ending up with double-freeing your memory ("move" semantics à la auto_ptr are best avoided unless you absolutely need it).
Since you can't use std::unique_ptr, you could create your own deleter class that would control the lifetime of the pointer in RAII fashion. To keep it simple this example doesn't wrap the actual pointer but exists alongside it; a safer approach would be to make a true smart pointer class.
class AutoFree
{
public:
AutoFree(void* p) : m_p(p)
{
}
~AutoFree()
{
free(m_p);
}
private:
void* m_p;
};
void my_class::my_func () {
char *mem = allocate_lots();
AutoFree mem_free(mem);
bool problem = use(mem);
if (problem)
throw my_exception("Oh noes! This will be caught higher up");
}
Is there any reason not to simply free the memory inside the if clause?
if (problem) {
free (mem);
throw my_exception ("Drat!");
}
Use unique_ptr: http://coliru.stacked-crooked.com/view?id=cd3f0fc64d99cc07a2350e2ff9686500-542192d2d8aca3c820c7acc656fa0c68
#include <stdexcept>
#include <iostream>
#include <memory>
/* old_library.c */
char *allocate_lots()
{
return static_cast<char*>(malloc(1024));
}
struct my_exception : virtual std::exception {
const char* const msg;
my_exception(const char* const msg) : msg(msg) {}
const char* what() const noexcept { return msg; }
};
struct my_class
{
struct Free { void operator() (char* p) const { free(p); } };
/* my_prog.cpp */
void my_func()
{
std::unique_ptr<char, Free> mem;
mem.reset(allocate_lots());
bool problem = use(mem.get());
if(problem)
{
throw my_exception("Oh noes! This will be caught higher up");
}
}
static bool use(char*) { return true; }
};
int main()
{
my_class prog;
prog.my_func();
}

QSQLTableModel inheritor and QTableView

I wrote QSQLTableModel inheritor for working with qml and it's work well. I need use it with QTableView too, data shows, but I cannot modify it - when I edit everything is ok, but all changes drop when I get out from field (I know about editStrategy, but the problem occurs earlier). I suppose that something wrong with virtual function, but I cant undestant what. If i create QSqlTableModel with the same parameters, everything is ok. Somebody have any idea how can i fix this? My code:
h:
class ListModel : public QSqlTableModel
{
Q_OBJECT
Q_PROPERTY( int count READ rowCount() NOTIFY countChanged())
signals:
void countChanged();
public:
Q_INVOKABLE QVariant data(const QModelIndex &index, int role) const;
ListModel(QObject *parent, QSqlDatabase _db):QSqlTableModel(parent,_db){this->setEditStrategy(QSqlTableModel::OnManualSubmit);}
void applyRoles();
#ifdef HAVE_QT5
virtual QHash<int, QByteArray> roleNames() const{return roles;}
#endif
private:
int count;
QHash<int, QByteArray> roles;
};
cpp:
//based on http://qt-project.org/wiki/How_to_use_a_QSqlQueryModel_in_QML
void ListModel::applyRoles()
{
roles.clear();
qDebug()<<"\n"<<this->tableName();
for (int i = 0; i < this->columnCount(); i++) {
QString role=this->headerData(i, Qt::Horizontal).toString();
roles[Qt::UserRole + i + 1] = QVariant(role).toByteArray();
qDebug()<<this->headerData(i, Qt::Horizontal);
}
#ifndef HAVE_QT5
setRoleNames(roles);
#endif
}
QVariant ListModel::data(const QModelIndex &index, int role) const{
QVariant value;
if(role < Qt::UserRole)
{
value = QSqlQueryModel::data(index, role);
}
else {
int columnIdx = role - Qt::UserRole - 1;
QModelIndex modelIndex = this->index(index.row(), columnIdx);
value = QSqlQueryModel::data(modelIndex, Qt::DisplayRole);
}
return value;
}
UPD
I understood that the problem is in data method's quantifier const, if I remove it everything is ok with QTableView, but I cant get data from model with gml's listviews. I see only one solution - replace interition from QSqlTableModel with aggregation it, but maybe someone knows better solution?
Summary: Solved with strange hack - inherited from QSqlRelationalTableModel instead QSqlTableModel, I think the reason is that QSqlRelationalTableModel has rewritten non virtual method data

Custom SWIG Wrapping to Handle Nested C Structures

I have the below C struct that has a couple nested structures that have proven to be difficult to deal with using my knowledge of SWIG. Everything below is easily wrapped by SWIG execept for saddr (C socket address) and mac[6] (C array representing a MAC address). Since SWIG gives me the pointer value (SWIGTYPE_p_unsigned_char and SWIGTYPE_p_sockaddr), I would like to somehow call a helper C function to convert the pointer to a char*. I have the helper function, but I don't know the best way to plug this into SWIG. Is there any way to configure the getMac() and getSaddr() to call the helper function?
C Structure Trying To Wrap:
%rename (Details) details_t_;
typedef struct details_t_ {
uint16_t code;
char *name;
**sockaddr *saddr;**
uint32_t saddr_len;
uint8_t flag;
ios_boolean is_child;
**unsigned char mac[6];**
} details_t;
Generated Java Code:
public void setMac(SWIGTYPE_p_unsigned_char value) {
TestJNI.Details_mac_set(swigCPtr, this, SWIGTYPE_p_unsigned_char.getCPtr(value));
}
public SWIGTYPE_p_unsigned_char getMac() {
long cPtr = TestJNI.Details_mac_get(swigCPtr, this);
return (cPtr == 0) ? null : new SWIGTYPE_p_unsigned_char(cPtr, false);
}
public void setSaddr(SWIGTYPE_p_sockaddr value) {
TestJNI.Details_saddr_set(swigCPtr, this, SWIGTYPE_p_sockaddr.getCPtr(value));
}
public SWIGTYPE_p_sockaddr getSaddr() {
long cPtr = TestJNI.Details_saddr_get(swigCPtr, this);
return (cPtr == 0) ? null : new SWIGTYPE_p_sockaddr(cPtr, false);
}
Proposed SWIG.i Changes:
%module Test
%rename (realId) details_t_::mac;
%typemap(javacode) struct details_t_ %{
public String getMac() {
return Test.getMacAddressAsString(this);
//this is a pointer to details_t_ struct
}
%};
%rename (Details) details_t_;
typedef struct details_t_ {
uint16_t code;
char *name;
**sockaddr *saddr;**
uint32_t saddr_len;
uint8_t flag;
ios_boolean is_child;
**unsigned char mac[6];**
} details_t;
You can do this with a javacode typemap, e.g.:
%module test
%rename (realId) Sample::id;
%typemap(javacode) struct Sample %{
public byte getId() {
return 100-getRealId(); // Transform the real call
}
public void setId(byte value) {
setRealId(value+100);
}
%};
struct Sample {
char id;
};
Renames the generated getId() and setId(), but provides a Java get/set which can be written in terms of the SWIG generated (but renamed) one. You might want to make the SWIG generated ones private though.

Implementing a good C++0x error_condition?

I try to figure out how the new system_error together with error_code, error_category and not the least the (meant to implement portable error reporting) error_condition should be used.
I think by reading boost.system I understand how I should use error_codes and error_category. The description leaves out how this is used in conjunction when throwing an exception with ´system_error`, but from the interface from that class I can guess.
class system_error : public runtime_error {
public:
// [...]
system_error(error_code ec, const string& what_arg);
system_error(int ev, const error_category& ecat, const string& what_arg);
system_error(int ev, const error_category& ecat);
// [...]
So, I throw a system_error-exception with the right int+error_category or error_code with its error_category()-method.
But whats the way to provide the portable interface with error_condition?
Both error_code and error_category both have method default_error_condition:
class error_category {
public:
// [...]
virtual error_condition default_error_condition(int ev) const noexcept;
// [...]
class error_code {
public:
// [...]
error_condition default_error_condition(int ev) const noexcept;
// [...]
The error_category-Instances should be pre-created, for example (user-code):
struct AppCategory : public error_category {
const char *name() const noexcept override {
return "application"; }
string message(int ev) const override {
switch(ev) {
case 14: return "error message";
default: return "???";
}
}
error_condition default_error_condition(int ev) const noexcept override {
... ??? ...
}
};
My questions implementing this:
Should I implement default_error_condition in error_category, and how?
Or how do I connect error_codes to the proper error_conditions,
and should I pre-construct error_condition instances?
A class error_code is not supposed to be provided by the user (me), right?
Is there a good example where I can take a look at code how error_condition is supposed to be extended by the user, in conjunction with system_error-exceptions?
If the error codes for your error category can be mapped to one of the std::errc error codes then default_error_condition should do that mapping, and return a std::error_condition with a category of std::generic_category() and a value of the corresponding std::errc enum value. Otherwise it should return an error_condition referring to that category.