A constructor with an integer parameter (constructs an SDL containing that integer only.
A default constructor (constructs an empty SDL)
I wrote these like that;
doublylinkedlist::doublylinkedlist(){
head=NULL;
tail=NULL;
}
//***********************************************************************************************
//A constructor with an integer parameter (constructs an SDL containing that integer only). *
//***********************************************************************************************
doublylinkedlist::doublylinkedlist(int number){
head->num =number;
tail=head;
}
but there is an error window about unhandled exception access violation writing location at
head->num=number;
line. Where is the problem ? and also this is my header file if you want to take a look :
#include <iostream>
#ifndef _HW3_H
#define _HW3_H
using namespace std;
struct node
{
int num;
node * left;
node * right;
node::node(){}
node::node(const int &integer, node *pointer, node *ptr):num(integer),left(pointer),right(ptr){}
};
class doublylinkedlist
{
private:
node *head;
node *tail;
int size;
public:
doublylinkedlist();
doublylinkedlist(int);
doublylinkedlist(const doublylinkedlist &);
~doublylinkedlist();
node* clone() const;
node *remove() const;
node *mergedlists(const doublylinkedlist &);
const doublylinkedlist & operator+(const doublylinkedlist &);
const doublylinkedlist & operator=(const doublylinkedlist &);
};
#endif
You need to initialize your head pointer first with a pointer to a node object:
doublylinkedlist::doublylinkedlist(int number)
: head(new node())
{
head->num =number;
tail=head;
}
The error occoured, because there was no node object "behind" the pointer
Related
I made a c++ class following this.
#include <string>
#include <vector>
namespace Test
{
typedef std::pair<int, int> Values;
class Configuration
{
public:
Configuration(std::string);
Configuration(const Configuration&);
~Configuration();
void setMinVal(int);
void setMaxVal(int);
void setVals(Values);
std::string getPath();
int getMinVal();
int getMaxVal();
Values getVals();
private:
std::string path;
int minVal;
int maxVal;
};
I made swig file following this:
%module Test
%include <std_string.i>
%include <std_vector.i>
%include <std_pair.i>
%{
#include "Test.h"
%}
%template(Values) std::pair<int, int>;
namespace Test {
class Configuration
{
public:
Configuration(std::string);
~Configuration();
void setMinVal(int);
void setMaxVal(int);
void setVals(std::pair<int, int>);
std::string getPath();
int getMinVal();
int getMaxVal();
std::pair<int, int> getVals();
};
}
I run swig command line and compile in visual studio.
But it occurs
error C4703: potentially uninitialized local pointer variable 'p' used
In this wrapper line:
value_type *p;
swig_type_info *descriptor = swig::type_info<value_type>();
res = descriptor ? SWIG_ConvertPtr(obj, (void **)&p, descriptor, 0) : SWIG_ERROR;
if (SWIG_IsOK(res) && val) *val = p;
In 4th line.
How can I fix it?
Thanks.
I have Qt/QML app that connects to database and now I would like to fetch data through sublcassed QSqlQueryModel:
#ifndef UEPEOPLEMODEL_H
#define UEPEOPLEMODEL_H
#include <QImage>
#include <QVariant>
#include <QStringList>
#include <QDebug>
#include <QHash>
#include <QByteArray>
#include <QSqlError>
#include <QSqlQueryModel>
#include <QSqlRecord>
#include <QModelIndex>
#include <QQuickImageProvider>
#include <QByteArray>
#include <QSqlRecord>
#include <QDebug>
#include <QSqlQuery>
#include "../settings/uedefaults.h"
#include "../settings/uetypes.h"
class UePeopleModel : public QSqlQueryModel,
public QQuickImageProvider
{
Q_OBJECT
private:
QSqlDatabase m_ueDb;
private:
QSqlDatabase ueDatabase() const
{ return this->m_ueDb; }
void ueSetDatabase(const QSqlDatabase& database)
{ this->m_ueDb=database; }
public:
UePeopleModel(QObject *parent=0);
~UePeopleModel();
QVariant data(const QModelIndex &index,
int role) const Q_DECL_OVERRIDE;
QImage ueImage(const QString &id) const;
QImage requestImage(const QString &id,
QSize *size,
const QSize &requestedSize);
UeTypeRoles roleNames() const;
public:
static const int ueRoleName=Qt::UserRole+1;
static const int ueRoleImage=Qt::UserRole+2;
};
#endif // UEPEOPLEMODEL_H
and here is implementation:
#include "uepeoplemodel.h"
UePeopleModel::UePeopleModel(QObject* parent)
: QSqlQueryModel(parent),
QQuickImageProvider(QQmlImageProviderBase::Image,
QQmlImageProviderBase::ForceAsynchronousImageLoading)
{
//QSqlDatabase db;
if(!QSqlDatabase::connectionNames().contains(UePosDatabase::UeDatabaseConnectionNames::DATABASE_CONNECTION_NAME_PEOPLE,
Qt::CaseInsensitive))
{
this->ueSetDatabase(QSqlDatabase::addDatabase(UePosDatabase::DATABASE_DRIVER,
UePosDatabase::UeDatabaseConnectionNames::DATABASE_CONNECTION_NAME_PEOPLE));
} // if
this->ueDatabase().setHostName(/*this->uePosSettings()->ueDbHostname()*/UePosDatabase::UeDatabaseConnectionParameters::DATABASE_HOSTNAME);
this->ueDatabase().setDatabaseName(/*this->uePosSettings()->ueDbName()*/UePosDatabase::UeDatabaseConnectionParameters::DATABASE_NAME);
this->ueDatabase().setUserName(/*this->uePosSettings()->ueDbUser()*/UePosDatabase::UeDatabaseConnectionParameters::DATABASE_USERNAME);
this->ueDatabase().setPassword(/*this->uePosSettings()->ueDbPassword()*/UePosDatabase::UeDatabaseConnectionParameters::DATABASE_PASSWORD);
if(this->ueDatabase().open())
{
this->setQuery(UePosDatabase::UeSqlQueries::UeTablePeople::SQL_QUERY_GET_ALL_PEOPLE,
this->ueDatabase());
//qDebug() << this->ueDatabase().lastError().text();
}
else
{
qDebug() << this->ueDatabase().lastError().text();
}
} // default constructor
UePeopleModel::~UePeopleModel()
{
} // default destructor
QVariant UePeopleModel::data(const QModelIndex &index,
int role) const
{
QVariant value=QVariant();
switch(role)
{
case ueRoleImage:
{
value=this->record(index.row()).value(UePosDatabase::UeTableIndexes::UeTablePeople::INDEX_IMAGE).toByteArray();
break;
} // case
case ueRoleName:
{
value=this->record(index.row()).value(UePosDatabase::UeTableIndexes::UeTablePeople::INDEX_NAME).toString();
break;
} // case
default:
return value;
} // switch
return QSqlQueryModel::data(index,
role);//value;
} // data
QImage UePeopleModel::ueImage(const QString &id) const
{
return QImage::fromData(this->record(id.toInt()).value(UePosDatabase::UeTableIndexes::UeTablePeople::INDEX_IMAGE).toByteArray(),
"PNG");
} // image
QImage UePeopleModel::requestImage(const QString &id,
QSize *size,
const QSize &requestedSize)
{
Q_UNUSED(requestedSize);
QImage image=this->ueImage(id);
*size = image.size();
return image;
} // requestImage
UeTypeRoles UePeopleModel::roleNames() const
{
UeTypeRoles roles;
const int iRoleName=UePeopleModel::ueRoleName;
const int iRoleImage=UePeopleModel::ueRoleImage;
roles.insert(iRoleName,
"ueRoleName");
roles.insert(iRoleImage,
"ueRoleImage");
return roles;
} // roleNames
Now, the problem is I get emtpty values from database, and therefore qml outputs errors:
> qrc:/gui/windows/UeKeypad.qml:140:43: Unable to assign [undefined] to
> QString qrc:/gui/windows/UeKeypad.qml:140:43: Unable to assign
> [undefined] to QString qrc:/gui/windows/UeKeypad.qml:118:33: QML
> Image: Failed to get image from provider:
> image://uepeoplemodel/undefined qrc:/gui/windows/UeKeypad.qml:118:33:
> QML Image: Failed to get image from provider:
> image://uepeoplemodel/undefined qrc:/gui/windows/UeKeypad.qml:140:43:
> Unable to assign [undefined] to QString
> qrc:/gui/windows/UeKeypad.qml:140:43: Unable to assign [undefined] to
> QString qrc:/gui/windows/UeKeypad.qml:140:43: Unable to assign
> [undefined] to QString qrc:/gui/windows/UeKeypad.qml:140:43: Unable to
> assign [undefined] to QString qrc:/gui/windows/UeKeypad.qml:118:33:
> QML Image: Failed to get image from provider:
> image://uepeoplemodel/undefined qrc:/gui/windows/UeKeypad.qml:118:33:
> QML Image: Failed to get image from provider:
> image://uepeoplemodel/undefined qrc:/gui/windows/UeKeypad.qml:118:33:
> QML Image: Failed to get image from provider:
> image://uepeoplemodel/undefined qrc:/gui/windows/UeKeypad.qml:118:33:
> QML Image: Failed to get image from provider:
> image://uepeoplemodel/undefined
Why am I getting empty values from table?!
Hmm, I've been doing research on problem, and in Qt docs it states:
If the model is not initialized, an empty record will be returned.
The link to docs: QSqlQueryModel::record. This might be the problem, however, I initialize UePeopleModel in main.cpp:
int main(int argc, char *argv[])
{
QApplication app(argc, argv);
QQmlApplicationEngine engine;
UePeopleModel* uePeopleModel=new UePeopleModel(qApp);
engine.rootContext()->setContextProperty("uePeopleModel",
uePeopleModel);
engine.load(QUrl(QStringLiteral("qrc:/main.qml")));
return app.exec();
}
What am I still missing? I've checked db connection numerous times, it is ok, I also get field names from table, but no data.
Hmm, I've added debug code to QVariant UePeopleModel::data(const QModelIndex &index, int role) const method:
QVariant UePeopleModel::data(const QModelIndex &index,
int role) const
{
switch(role)
{
case ueRoleImage:
{
return this->record(index.row()).value(UePosDatabase::UeTableIndexes::UeTablePeople::INDEX_IMAGE).toByteArray();
break;
} // case
case ueRoleName:
{
int nrrecords=this->rowCount(QModelIndex());
QString name=this->record(index.row()).value(UePosDatabase::UeTableIndexes::UeTablePeople::INDEX_NAME).toString();;
return this->record(index.row()).value(UePosDatabase::UeTableIndexes::UeTablePeople::INDEX_NAME).toString();
} break; // case
case ueRolePassword:
{
QString password=this->record(index.row()).value(UePosDatabase::UeTableIndexes::UeTablePeople::INDEX_APPPASSWORD).toString();
return this->record(index.row()).value(UePosDatabase::UeTableIndexes::UeTablePeople::INDEX_APPPASSWORD).toString();
} break; // case
default:
return QVariant();
} // switch
return QSqlQueryModel::data(index,
role);//value;
} // data
and after the line int nrrecords=this->rowCount(QModelIndex()); I've set a breakpoint, the temp variable nrrecord holds value 5 - which is excatly number of records in database! Why is then method's parameter index empty?? The data() method is being called from QML file via QML items model property.
There are following problems at least:
Your switch cases all fall through (you must break after each one).
You don't need any accessors to the private members, you are supposed to use them directly. That's why they are private. Accessors are used as encapsulation when you want to isolate the implementation details from public (or protected) interface. Remove the accessors for m_ueDb and use the member directly.
Your implementation of data will only provide values for image roles. You must forward the default role access to the base class's data():
QVariant UePeopleModel::data(const QModelIndex &index, int role) const
{
switch(role) {
case ueRoleImage:
for(int iIndex=0; iIndex<this->record().count(); iIndex++) {
qDebug() << this->record().fieldName(iIndex) <<
<< this->record().value(iIndex) <<
<< index.row();
}
return record(index.row()).value(
UePosDatabase::UeTableIndexes::UeTablePeople::INDEX_IMAGE).toByteArray();
case ueRoleName:
return record(index.row()).value(
UePosDatabase::UeTableIndexes::UeTablePeople::INDEX_NAME).toString();
}
return QSqlQueryModel::data(index, role);
}
You should never use the <QtModule/QtHeader> include style. That you do indicates that your .pro file doesn't declare the use of the sql module and/or that you haven't re-run qmake on your project after adding the module to the project (you should have QT += sql somewhere in your .pro file). Fix as follows:
// CORRECT
#include <QSqlError>
// WRONG
#include <QtSql/QSqlError>
I have a constructor where as first 2 parameteres I would like to pass:
ID3D11ShaderResourceView* as a steady downloaded texture OR
const CHAR* as a filename to downlowd this texture and assign it to a class ID3D11ShaderResourceView* member (with following release on demand), but I can not understand the way I should do it correctly. it looks this way:
class {button
public
button() {};
button(data1 (or texture or filname), data2 (or texture or filname), rest data....);
...
~button();
}
so I tried:
templates but failed, may be cause of knowledge lack, templates
define one type while I need a choice of 2. Varradic templates, or I didnt get them right but they mean undetermined amount of variables when I need to differ only 2 first.
Unions but it had conflict with class variable set - said could not match const char [amount] with const char* and unions do not work with std::string.
tried void* with typeid.name() but it always showed me "void *"
I don't want to overload constructors, becuase this will create 4+ of them barely differing one from another. Do you think boost::variant helps me in this case? Is there any smooth and effective way to build that kind of constructor? My c++ knowledge is on beginning level, sorry if its a duplicate topic, read all it suggested to me while creating it but didn't seem to find out anything closely similar, thanks:)
Update:
Applied boost::any, got next results:
class button : public frame {
public:
button() {};
button(boost::any _texture,
boost::any _hover_texture,
...
};
if (_texture.type() == typeid(ID3D11ShaderResourceView*)) texture = boost::any_cast<ID3D11ShaderResourceView*>(_texture);
if (_texture.type() == typeid(const char*))
{
if ( FAILED(D3DX11CreateShaderResourceViewFromFile(gvDevice,boost::any_cast<const char*>(_texture), NULL, NULL, &texture, NULL )) )
mboxout( "loading texture failed.", "UI texture load error", true );
};
if (_hover_texture.type() == typeid(ID3D11ShaderResourceView*)) hover_texture = boost::any_cast<ID3D11ShaderResourceView*>(_hover_texture);
if (_hover_texture.type() == typeid(const char*))
{
if ( FAILED(D3DX11CreateShaderResourceViewFromFile(gvDevice, boost::any_cast<const char*>(_hover_texture), NULL, NULL, &hover_texture, NULL )) )
mboxout( "loading texture failed.", "UI texture load error", true );
};
Is it the only possible decision because this one seems akward for me? Thanks :)
As always, when you have combinatoric explosion/tedious repetition, refactor your code into reusable units.
In this case, your constructor could be just
template <typename T1, typename T2>
button(T1 const& texture, T2 const& hover_texture)
: _texture(load(texture)),
_hover_texture(load(hover_texture))
{
};
And all the loading logic would be inside... you guess it the load function. A sample implementation of that:
static ID3D11ShaderResourceView* load(ID3D11ShaderResourceView* v){
return v; // just return the resources passed in
}
static ID3D11ShaderResourceView* load(char const* fname) {
ID3D11ShaderResourceView* p = NULL;
if (FAILED(D3DX11CreateShaderResourceViewFromFile(gvDevice, fname, NULL, NULL, &p, NULL)))
throw std::runtime_error(std::string("loading texture failed (") + fname + ")");
return p;
}
Note: while we were at it we separated UI from business logic. You do not want to display messageboxes from inside constructors. Ever. You just want to notify the caller of the problem and the caller decides what to do (use another resource, try a different path, retry a download, write a warning message to the log, shut down etc.)
Full Demo
Live On Coliru
#include <iostream>
#include <stdexcept>
///////////////////////////////////////////////////////
// mocking ID3D*
struct ID3D11ShaderResourceView;
enum ERROR_CODE { ERR_OK };
#define FAILED(e) (ERR_OK != (e))
static int gvDevice = 42;
ERROR_CODE D3DX11CreateShaderResourceViewFromFile(int, char const* fname, void*, void*, ID3D11ShaderResourceView**, void*) {
std::cout << "Loaded from " << fname << "\n";
return ERR_OK;
}
//
///////////////////////////////////////////////////////
struct frame{ virtual ~frame() = default; };
class button : public frame {
public:
button() {};
template <typename T1, typename T2>
button(T1 const& texture, T2 const& hover_texture)
: _texture(load(texture)),
_hover_texture(load(hover_texture))
{
};
private:
// TODO Rule-Of-Three constructor/destructorl
// SUGGEST: Rule-Of-Zero using shared pointers instead
ID3D11ShaderResourceView* _texture;
ID3D11ShaderResourceView* _hover_texture;
static ID3D11ShaderResourceView* load(ID3D11ShaderResourceView* v) { return v; }
static ID3D11ShaderResourceView* load(char const* fname) {
ID3D11ShaderResourceView* p = NULL;
if (FAILED(D3DX11CreateShaderResourceViewFromFile(gvDevice, fname, NULL, NULL, &p, NULL)))
throw std::runtime_error(std::string("loading texture failed (") + fname + ")");
return p;
}
};
#include <cassert>
int main() {
ID3D11ShaderResourceView* default_texture = NULL;
assert(!FAILED( D3DX11CreateShaderResourceViewFromFile(gvDevice, "default_texture.bin", NULL, NULL, &default_texture, NULL)));
try {
button button1("t1.bin", "hover1.bin");
button button2(default_texture, "hover2.bin");
button button3("t3.bin", default_texture);
button button4(default_texture, default_texture);
} catch(std::exception const& e) {
std::cout << "Oops: " << e.what() << "\n";
}
}
Prints:
Loaded from default_texture.bin
Loaded from t1.bin
Loaded from hover1.bin
Loaded from hover2.bin
Loaded from t3.bin
There's still a lot to be improved (see the comments, e.g.) but this is a start.
#include <stdio.h>
#include <string.h>
void func1 (void) { printf( "1\n" ); }
void func0 (void) { printf( "0\n" ); }
typedef struct {
void (*func0)(void);
void (*func1)(void);
}mainJT;
static const mainJT coreJT = {
core_func0,
core_func1
};
mainJT currJT;
int main()
{
currJT=coreJT;
coreJT.core_func0();
getchar();
return 0;
}
Please help me fix the errors, I am sure I am making some obvious mistakes. Thanks.
Your question isn't quite clear but I see what I can find.
typedef struct {
void (*func0)(void);
void (*func1)(void);
} mainJT;
Here you are declaring a struct with function pointer members func0 and func1. Then you are trying to define a coreJT variable via an initializer list:
static const mainJT coreJT = {
core_func0,
core_func1
};
But this doesn't work, because there are no functions called core_func0 or core_func1!
Also you try to call
coreJT.core_func0();
which is also incorrect since your struct doesn't have a member of name core_func0.
For a possible solution try renaming your functions like so:
void core_func1 (void) { printf( "1\n" ); }
void core_func0 (void) { printf( "0\n" ); }
and call your function pointer by
coreJT.func0();
i see lot of errors:
for eg: the correct way of initializing a structure is :
/* Define a type point to be a struct with integer members x, y */
typedef struct {
int x;
int y;
} point;
/* Define a variable p of type point, and initialize all its members inline! */
point p = {1,2};
so your part of the code is :
mainJT coreJT = {
core_func0;
core_func1;
};
completely wrong.
also where are the functions core_func1 core_func0 are declared and defined .i cannot see them.
i guess you first need to go through structures in c
I'm using SWIG to make C# bindings that are compatible with the compact framework (WinCE). I've got most of the immediate issues worked through, but my next blocker is that some of the functions return a double. Wrappers are generated but they fail at run time because the CF framework will not marshal non-integral datatypes (http://msdn.microsoft.com/en-us/library/aa446536.aspx)
My example failure is an attempt to wrap this function:
double getMaxMagnification() const
{
return m_maxMag;
}
SWIG generates this wrapper:
SWIGEXPORT double SWIGSTDCALL CSharp_LTIImageFilter_getMaxMagnification(void * jarg1) {
double jresult ;
LizardTech::LTIImageFilter *arg1 = (LizardTech::LTIImageFilter *) 0 ;
double result;
arg1 = (LizardTech::LTIImageFilter *)jarg1;
result = (double)((LizardTech::LTIImageFilter const *)arg1)->getMaxMagnification();
jresult = result;
return jresult;
}
which is NG because it requires marshalling a double return value.
I manually changed this to return the double via a passed-in pointer:
SWIGEXPORT void SWIGSTDCALL CSharp_LTIImageFilter_getMaxMagnification(void * jarg1, void *jarg2) {
fprintf(stderr, "CSharp_LTIImageFilter_getMaxMagnification\n");
//double jresult ;
LizardTech::LTIImageFilter *arg1 = (LizardTech::LTIImageFilter *) 0 ;
double result;
arg1 = (LizardTech::LTIImageFilter *)jarg1;
result = (double)((LizardTech::LTIImageFilter const *)arg1)->getMaxMagnification();
*((double*)jarg2) = result;
//jresult = result ;
//return jresult;
}
After making the corresponding changes in the C# declaration file and implementation class, this works as expected.
That is,
Interop Declaration
NG:
[DllImport("LizardTech_SdkInterop.dll", EntryPoint="CSharp_LTIImageFilter_getMaxMagnification")]
public static extern double LTIImageFilter_getMaxMagnification(IntPtr jarg1);
OK:
[DllImport("LizardTech_SdkInterop.dll", EntryPoint="CSharp_LTIImageFilter_getMaxMagnification")]
public static extern void LTIImageFilter_getMaxMagnification(IntPtr jarg1, ref double jarg2);
Implementation class
NG:
public override double getMaxMagnification() {
double ret = RasterSDKPINVOKE.LTIImageFilter_getMaxMagnification(swigCPtr);
return ret;
}
OK:
public override double getMaxMagnification() {
double ret = 0;
RasterSDKPINVOKE.LTIImageFilter_getMaxMagnification(swigCPtr, ref ret);
return ret;
}
How can I get SWIG to do this for me? I think the tasks are:
(a) change the return type of the wrapper function (only) from double to void
(b) add an argument (pointer to double) to the argument list so that the wrapper can send back the value that way
(c) make the interop declaration reflect the above two changes
(d) make the C# wrapper invoke the new wrapper function.
As always big-picture re-orientation is appreciated.
I'm indebted to David Piepgrass for this. It's not perfect but its good enough for me.
http://sourceforge.net/mailarchive/message.php?msg_id=26952332
////////////////////////////////////////////////////////////////////////////////
// Floating-point value marshalling for .NET Compact Framework:
// All floating-point values must be passed by reference. MULTITHREADING DANGER:
// For return values a pointer to a static variable is returned.
%define %cs_compact_framework_float(FLOAT)
%typemap(ctype, out="FLOAT*") FLOAT "FLOAT*"
%typemap(ctype, out="FLOAT*") FLOAT*, FLOAT&, const FLOAT& "FLOAT*"
%typemap(imtype, out="IntPtr") FLOAT, FLOAT*, FLOAT&, const FLOAT& "ref FLOAT"
%typemap(cstype, out="FLOAT") FLOAT, const FLOAT& "FLOAT"
%typemap(cstype, out="FLOAT") FLOAT*, FLOAT& "ref FLOAT"
%typemap(in) FLOAT %{ $1 = *$input; %}
%typemap(in) FLOAT*, FLOAT&, const FLOAT& %{ $1 = $input; %}
%typemap(out, null="NULL") FLOAT, FLOAT*, FLOAT&, const FLOAT& %{
// Not thread safe! FLOAT must be returned as a pointer in Compact Framework
static FLOAT out_temp;
out_temp = $1;
$result = &out_temp;
%}
%typemap(csin) FLOAT, const FLOAT& "ref $csinput"
%typemap(csin) FLOAT*, FLOAT& "ref $csinput"
%typemap(csout, excode=SWIGEXCODE) FLOAT, FLOAT*, FLOAT&, const FLOAT& {
IntPtr ptr = $imcall;$excode
FLOAT ret = (FLOAT)Marshal.PtrToStructure(ptr, typeof(FLOAT));
return ret;
}
%typemap(csvarout, excode=SWIGEXCODE2) FLOAT, FLOAT*, FLOAT&, const FLOAT&
%{
get {
IntPtr ptr = $imcall;$excode
FLOAT ret = (FLOAT)Marshal.PtrToStructure(ptr, typeof(FLOAT));
return ret;
}
%}
%enddef
%cs_compact_framework_float(float)
%cs_compact_framework_float(double)