Class Problem (c++ and prolog) - c++

I am using the C++ interface to Prolog (the classes and methods of SWI-cpp.h). For working out a simple backtracking that john likes mary and emma and sara:
likes(john, mary).
likes(john, emma).
likes(john, ashley).
I can just do:
{
PlFrame fr;
PlTermv av(2);
av[0] = PlCompound("john");
PlQuery q("likes", av);
while (q.next_solution())
{
cout << (char*)av[1] << endl;
}
}
This works in a separate code, so the syntax is correct. But I am also trying to get this
simple backtracking to work within a class:
class UserTaskProlog
{
public:
UserTaskProlog(ArRobot* r);
~UserTaskProlog();
protected:
int cycles;
char* argv[1];
ArRobot* robot;
void logTask();
};
This class works fine, with my cycles variable incrementing every robot cycle. However, when I run my main code, I get an Unhandled Exception error message:
UserTaskProlog::UserTaskProlog(ArRobot* r) : robotTaskFunc(this, &UserTaskProlog::logTask)
{
cycles = 0;
PlEngine e(argv[0]);
PlCall("consult('myFile.pl')");
robot->addSensorInterpTask("UserTaskProlog", 50, &robotTaskFunc);
}
UserTaskProlog::~UserTaskProlog()
{
robot->remSensorInterpTask(&robotTaskFunc);
// Do I need a destructor here for pl?
}
void UserTaskProlog::logTask()
{
cycles++;
cout << cycles;
{
PlFrame fr;
PlTermv av(2);
av[0] = PlCompound("john");
PlQuery q("likes", av);
while (q.next_solution())
{
cout << (char*)av[1] << endl;
}
}
}
I have my opening and closing brackets for PlFrame. I have my frame, my query, etc... The exact same code that backtracks and prints out mary and emma and sara. What am I missing here that I get an error message?
Here is what I think the code should do: I expect mary and emma and sara to be printed out once, every time cycles increments. However, it opens SWI-cpp.h file automatically and points to class PlFrame. What is it trying to tell me? I don't see anything wrong with my PlFrame class declaration.
Thanks,

You cannot pass pointers to instance methods like this, you probably have to create C function wrapper for passing to addSensorInterpTask(). This seems to be the root of your problem, as robot calls the method with incorrect parameters. Also, you should catch PlException and check what it tells you.
Anyway, your example cannot be compiled as it is, since it is incomplete (what is ArRobot?) and imprecise (ashley v.s. sara). Please try to imagine how other people could reproduce your problem without much a of a hassle before submitting a question.

Related

how to correctly pass data structures between custom llvm passes

I have a Function pass, called firstPass, which does some analysis and populates:
A a;
where
typedef std::map< std::string, B* > A;
class firstPass : public FunctionPass {
A a;
}
typedef std::vector< C* > D;
class B {
D d;
}
class C {
// some class packing information about basic blocks;
}
Hence I have a map of vectors traversed by std::string.
I wrote associated destructors for these classes. This pass works successfully on its own.
I have another Function pass, called secondPass, needing this structure of type A to make some transformations. I used
bool secondPass::doInitialization(Module &M) {
errs() << "now running secondPass\n";
a = getAnalysis<firstPass>().getA();
return false;
}
void secondPass::getAnalysisUsage(AnalysisUsage &AU) const {
AU.addRequired<firstPass>();
AU.setPreservesAll();
}
The whole code compiles fine, but I get a segmentation fault when printing this structure at the end of my first pass only if I call my second pass (since B* is null).
To be clear:
opt -load ./libCustomLLVMPasses.so -passA < someCode.bc
prints in doFinalization() and exits successfully
opt -load ./libCustomLLVMPasses.so -passA -passB < someCode.bc
gives a segmentation fault.
How should I wrap this data structure and pass it to the second pass without issues? I tried std::unique_ptr instead of raw ones but I couldn't make it work. I'm not sure if this is the correct approach anyway, so any help will be appreciated.
EDIT:
I solved the problem of seg. fault. It was basically me calling getAnalysis in doInitialization(). I wrote a ModulePass to combine my firstPass and secondPass whose runOnModule is shown below.
bool MPass::runOnModule(Module &M) {
for(Function& F : M) {
errs() << "F: " << F.getName() << "\n";
if(!F.getName().equals("main") && !F.isDeclaration())
getAnalysis<firstPass>(F);
}
StringRef main = StringRef("main");
A& a = getAnalysis<firstPass>(*(M.getFunction(main))).getA();
return false;
}
This also gave me to control the order of the functions processed.
Now I can get the output of a pass but cannot use it as an input to another pass. I think this shows that the passes in llvm are self-contained.
I'm not going to comment on the quality of the data structures based on their C++ merit (it's hard to comment on that just by this minimal example).
Moreover, I wouldn't use the doInitialization method, if the actual initialization is that simple, but this is a side comment too. (The doc does not mention anything explicitly about it, but if it is ran once per Module while the runOn method is ran on every Function of that module, it might be an issue).
I suspect that the main issue seems to stem from the fact A a in your firstPass is bound to the lifetime of the pass object, which is over once the pass is done. The simplest change would be to allocate that object on the heap (e.g. new) and return a pointer to it when calling getAnalysis<firstPass>().getA();.
Please note that using this approach might require manual cleanup if you decide to use a raw pointer.

error: statement cannot resolve address of overloaded function C++

I am studying C++ by book and was trying to test simple coding for a looped game combat. A switch inside a while loop.
damage = greatsword[0] + player[1] - enemy[2]; endl;
error: statement cannot resolve address of overloaded function|
I have this error in 4 different code lines and in each one it has 'damage' so I assume its some problem with that. I have damage declared as an int and set to 0 before trying to change it to the attack value. I can provide more of the code if needed. I also tried changing the name from x to dmg to see if that was the problem
You have a trailing endl; which you probably did not mean to include. std::endl is a function which is used when printing to an output stream; usually you'll see cout << ... << endl;, but otherwise it should not be used.
std::endl, as used as a stream manipulator, is actually a function.
You probably achieve a similar or related error message by doing this
void f(); // don't need to define f()
int main()
{
f; // should be f() to call the function
}
So remove the statement endl;

Method can not initialize value c++

Firstly I initialize value in constructor in Ford Bellman claas
FordBellman::FordBellman() {
this->vertexCount=0;
this->vertexFirst=0;
this->edgeCount=0;
this->wage=0;
this->matrix=0;
this->distance=0;
this->predecessor=0;
}
next I have reference in argument of initialize method in FordBellman
void FordBellman::initialize(const AdjacencyMatrix &am)
{
this->vertexCount=am.getVertexCount();
this->vertexFirst=am.getVertexFirst();
this->edgeCount=am.getEdgeCount();
this->wage=am.getWage();
this->matrix=am.getMatrix();
cout << vertexCount;
cout << vertexFirst;
.....
}
in main class I do it in this way
int main() {
AdjacencyMatrix am;
FordBellman fb;
am.createFromFile("matrix.txt");
fb.initialize(am);
}
And if i call fb.initialize(am) console show nothing(should show cout )
Can you tell me what I do wrong ?
repo https://github.com/likoms/Graph/
When I tried to run code from github repository about you sad I got segmentation fault. The reason was in the file FordBellman.cpp line 42. There you didn't allocate array but you used it.
The reason why you didn't see anything is in the fact your program is terminated before it prints something. To be accurate it's happening inside of am.createFromFile("matrix.txt");
Try to write memory allocation for predecessor and I think your code will start working.
I'm a bit confused that you doesn't get message about segmentation fault. What development environment you use?

if statement in main function c++

Okay, probably a dumb question to you guys but I can't figure it out.
So I'm taking a c++ basics course in class and so far I'm struggling/crying.
I can't show you guys my code because I'm not allowed/there are consequences if I'm caught but I could probably give a example.
I'm using xcode. So when I compile, I get two errors below (image provided).
I searched for similar questions, but those seem too complex compared to what I'm doing. In addition, the only includes I have are iostream and string.
I know the problem occurs when I add an if statement in my main function. I know this because when I delete it, everything compiles as expected. Yet when I add it again to the main function, these errors occur.
So my question is, based on what I know, is it proper to add an if statements whenever in the main function?
Below is an example. I wrote the functions below and called above.
#include <iostream>
#include <string>
using namespace std;
// example functions that I just made up to explain the structure of my actual code.
//Don't bother trying to understand it. It's just to explain that
//I wrote my functions at the
// bottom and called it at the top.
int getNumberofWins(param1, param2);
string getTheName(int player1);
int executeCycle(string p1_name, string p2_name);
void stateWinner(string winner_name);
int main {
playerOne = getTheName(1);
playerTwo = getTheName(2);
r1 = executeCycle(playerOne, playerTwo);
r2= executeCycle(playerOne, playerTwo);
totalWin1 = getNumberOfWins(1, r1, r2);
totalWin2 = getNumberOfWins(2, r1, r2);
cout << totalWin1;
//This is the where I get the errors. When I delete the if statement,
//Everything compiles. When I add it, an error occurs.
if (totalWin1 == 2){
stateWinner(playerOne);
}
return 0;
}
string getTheName(int player1){
string playerOne;
string playerTwo;
if(player_number == 1){ code code code
}
}
int getNumberofWins (int param1, int param2){
code code code
}
int executeCycle(string p1_name, string p2_name){
code code code
}
void stateWinner(string winner_name){
if(!winner_name.empty()){
code code code
}
I hope it's fine if the code above isn't accurate. I think the point is that once I add my if statement to the main function, the two errors show up.
actually...now that I look at it, they both seem like similar errors. I just don't know why they both appear...
Sorry if this is an obvious answer or if it isn't clear.
The "announceWinner" function is not defined anywhere, ie there's no
void announceWinner () {
// code
}
anywhere. Either you haven't written it yet, or the file that contains it is not being compiled & linked with the main program.

c++ Log class inefficient?

I wrote a very simple Log class for a game im writing just to see some info in the terminal. But the way i did it bugs me because i feel its too inefficient. Every time i log something its constructor and destructor are called. So if i want to print the current frame rate (ex 60fps) the cont/desct are called 60 times a sec (creating and destroying 60 log objects a second). i dont want to keep passing a log object around the game every time i want to log something and i dont want to use signletons. is there a better solutions.
#include <iostream>
#include <sstream>
class Log
{
public:
Log() : os()
{
}
~Log()
{
fprintf(stderr, "%s\n", os.str().c_str());
}
std::ostringstream &Write()
{
os << "from log class: " << 1337 << "\t";
return os;
}
private:
std::ostringstream os;
};
int main(int argc, char *argv[])
{
Log().Write() << "Hello world " << 45;
return 0;
}
I would recommend to go with some existing logging framework. People put a lot of efforts to make it as fast and as flexible as possible.
Here is good description of existing logging frameworks:
https://stackoverflow.com/questions/696321/best-logging-framework-for-native-c
You are making an assumption that the constructor and destructor are inefficient. In my experience if they are declared in a header file (as yours are) and if they are simple (as yours are) then you can trust the compiler to inline them and do a very good job. The call to printf is going to dominate the time.