LLVM: "Export" class - class

I'd like to call this code from my program using LLVM:
#include <string>
#include <iostream>
extern "C" void hello() {
std::cout << "hello" << std::endl;
}
class Hello {
public:
Hello() {
std::cout <<"Hello::Hello()" << std::endl;
};
int hello() {
std::cout<< "Hello::hello()" << std::endl;
return 99;
};
};
I compiled this code to llvm byte code using clang++ -emit-llvm -c -o hello.bc hello.cpp and then I want to call it from this program:
#include <llvm/ExecutionEngine/ExecutionEngine.h>
#include <llvm/ExecutionEngine/GenericValue.h>
#include <llvm/ExecutionEngine/JIT.h>
#include <llvm/LLVMContext.h>
#include <llvm/Module.h>
#include <llvm/Target/TargetSelect.h>
#include <llvm/Support/MemoryBuffer.h>
#include <llvm/Support/IRReader.h>
#include <string>
#include <iostream>
#include <vector>
using namespace std;
using namespace llvm;
void callFunction(string file, string function) {
InitializeNativeTarget();
LLVMContext context;
string error;
MemoryBuffer* buff = MemoryBuffer::getFile(file);
assert(buff);
Module* m = getLazyBitcodeModule(buff, context, &error);
ExecutionEngine* engine = ExecutionEngine::create(m);
Function* func = m->getFunction(function);
vector<GenericValue> args(0);
engine->runFunction(func, args);
func = m->getFunction("Hello::Hello");
engine->runFunction(func, args);
}
int main() {
callFunction("hello.bc", "hello");
}
(compiled using g++ -g main.cpp 'llvm-config --cppflags --ldflags --libs core jit native bitreader')
I can call the hello() function without any problems.
My question is: how can I create a new instance of the Hello class using LLVM?
I'm getting a segmentation fault when I call Hello::Hello()
Thanks for any hints!!
Manuel

Running clang++ -emit-llvm on the given source won't emit Hello::Hello, and m->getFunction("Hello::Hello") wouldn't find it even if it were emitted. I would guess it's crashing because func is null.
Trying to directly call functions which aren't extern "C" from the LLVM JIT is generally not recommended... I'd suggest writing a wrapper like the following, and compiling it with clang (or using the clang API, depending on what you're doing):
extern "C" Hello* Hello_construct() {
return new Hello;
}

Related

why my code which includes hashfunction and unordered_set uncompilable?

#include <iostream>
#include <string>
#include <unordered_set>
using namespace std;
struct hashfunction{
size_t operator()(pair<string,int> x){
size_t ret=5381;
for(int i=0;i<x.first.length();i++){
ret=(ret<<5)+(ret)+x.first[i];
}
ret+=x.second;
return ret;
}
};
unordered_set<pair<string,int>,hashfunction> myset;
int main(void)
{
string a="123";
int b= 4;
myset.insert({a,b});
}
I am studying unordered_set and hashfunction. But the code above is not compilable. why not? Anyone can explain why it is not compilable and how to solve this problem?
const is needed after operator()(pair<string,int> x).

Thrust Device Vector iterator location

i am trying to find the index/location of an iterator, i use the thrust::distance(). however, it returns weird value.
the vector size is 10. and when i use this method it returns value of "131" .
here is a fully working example.
#include <thrust/device_vector.h>
#include <thrust/host_vector.h>
#include <thrust/reduce.h>
#include <thrust/extrema.h>
#include <iostream>
#include <iomanip>
#include <thrust/sort.h>
#include <thrust/copy.h>
#include <thrust/random.h>
#include <thrust/unique.h>
#include <thrust/reduce.h>
#include <thrust/iterator/constant_iterator.h>
using namespace std;
template <typename Vector>
void print_vector(const std::string& name, const Vector& v)
{
typedef typename Vector::value_type T;
std::cout << " " << std::setw(20) << name << " ";
thrust::copy(v.begin(), v.end(), std::ostream_iterator<T>(std::cout, ""));
std::cout << std::endl;
}
int main()
{
thrust::device_vector<int> x;
x.push_back(1);
x.push_back(10);
x.push_back(1);
x.push_back(11);
x.push_back(1);
x.push_back(11);
thrust::device_vector<int> y(10);
print_vector("Original",x);
thrust::sort(x.begin(),x.end());
print_vector("sort",x);
thrust::device_vector<int>::iterator it=thrust::unique(x.begin(),x.end());
std::cout<<*it<<std::endl;
//int newsize=it-y.begin();
int newsize=thrust::distance(y.begin(),it);
cout<<"nsz:"<<newsize<<endl;
return 0;
}
The iterator it is established with respect to the vector x:
thrust::device_vector<int>::iterator it=thrust::unique(x.begin(),x.end());
^ ^
But you are asking for the distance from this iterator to the beginning of the vector y:
int newsize=thrust::distance(y.begin(),it);
^
That doesn't make sense. There is no defined relationship between it and the vector y.
If you ask for the distance to the beginning of vector x instead, you'll get more sensible results:
$ cat t1244.cu
#include <thrust/device_vector.h>
#include <thrust/host_vector.h>
#include <thrust/reduce.h>
#include <thrust/extrema.h>
#include <iostream>
#include <iomanip>
#include <thrust/sort.h>
#include <thrust/copy.h>
#include <thrust/random.h>
#include <thrust/unique.h>
#include <thrust/reduce.h>
#include <thrust/iterator/constant_iterator.h>
using namespace std;
template <typename Vector>
void print_vector(const std::string& name, const Vector& v)
{
typedef typename Vector::value_type T;
std::cout << " " << std::setw(20) << name << " ";
thrust::copy(v.begin(), v.end(), std::ostream_iterator<T>(std::cout, " "));
std::cout << std::endl;
}
int main()
{
thrust::device_vector<int> x;
x.push_back(1);
x.push_back(10);
x.push_back(1);
x.push_back(11);
x.push_back(1);
x.push_back(11);
thrust::device_vector<int> y(10);
print_vector("Original",x);
thrust::sort(x.begin(),x.end());
print_vector("sort",x);
thrust::device_vector<int>::iterator it=thrust::unique(x.begin(),x.end());
std::cout<<*it<<std::endl;
//int newsize=it-y.begin();
int newsize=thrust::distance(x.begin(),it);
cout<<"nsz:"<<newsize<<endl;
return 0;
}
$ nvcc -o t1244 t1244.cu
$ ./t1244
Original 1 10 1 11 1 11
sort 1 1 1 10 11 11
10
nsz:3
$

Why does destructor cause segmentation fault?

All I do is construct a BNode object. The debugger says that the constructor is causing a segmentation fault. Does anyone know what the problem is here?
All I do is construct a BNode object. The debugger says that the constructor is causing a segmentation fault. Does anyone know what the problem is here?
#ifndef BTree_H
#define BTree_H
#include <iostream>
#include <fstream>
#include <cctype>
#include <string>
#include <sstream>
#include <cmath>
using namespace std;
template <typename T>
class BNode
{
public:
BNode();
BNode(int M);
~BNode();
int keyCount;
BNode *pointers;
T *keys;
};
template<typename T>
BNode<T>::BNode()
{
}
template<typename T>
BNode<T>::BNode(int M)
{
pointers = new BNode<T>[M];
keys = new T[M - 1];
}
template<typename T>
BNode<T>::~BNode()
{
delete[] pointers;
delete[] keys;
}
#endif
int main()
{
BNode<int> obj(5);
return 0;
}
You are deleting an array of pointers and keys, whereas you never defined these to be arrays.
Both of these are pointers.
You need to be freeing memory from the pointers, not arrays.
Try this:-
delete myPointer;
myPointer = NULL;
NOTE: If you're using C++, read about smart pointers. They'll come in handy!

how to call a function of c++ file in .m file?

I have a header file test.h
#ifndef __visibilty_test__test__
#define __visibilty_test__test__
#include <iostream>
using namespace std;
class test{
public:
void print(string s);
};
#endif
and test.mm
#include "test.h"
using namespace std;
void test:: print(string s){
cout << s << endl;
}
now I want to call print function in my AppDelegate.m file in an iOS Application. Can anyone help me?
Thanks in advance
Rename AppDelegate.m to AppDelegate.mm.
Call the method as you would in C++:
test t;
t.print("Hello");
Your object:
#include <iostream>
using namespace std;
class test
{
public:
void print(string s)
{
cout << s << endl;
}
};
call from mm file
test *t = new test;
t->print("hello");

Virtual Functions in Class Hierarchy

I suppose it is not such a clever question but i have been spending considerable time on it and still doesnt compile
Can you please explain why?
Thanks
1>------ Build started: Project: Ch17, Configuration: Release Win32 ------
1> p731.cpp
1>\\na-13\agnolucp\my documents\visual studio 2010\projects\ch17\ch17\Bear.h(29): error C2084: function 'std::ostream &Bear::print(std::ostream &) const' already has a body
1> \\na-13\agnolucp\my documents\visual studio 2010\projects\ch17\ch17\Bear.h(19) : see previous definition of 'print'
1>p731.cpp(16): error C2264: 'Bear::print' : error in function definition or declaration; function not called
========== Build: 0 succeeded, 1 failed, 0 up-to-date, 0 skipped ==========
//Endangered
#ifndef ENDAGERED
#define ENDAGERED
#include <iostream>
class Endangered {
public:
//virtual ~Endangered();
virtual std::ostream& print(std::ostream&) const;
// virtual so needs to be defined otherwise error
virtual void highlight() const;
};
//ZooAnimal
#ifndef ZOOANIMAL
#define ZOOANIMAL
#include<string>
class ZooAnimal {
public:
ZooAnimal();
ZooAnimal(std::string animal, bool exhibit,
std::string family): Name(animal),
OnExhibition(exhibit),
FamilyName(family) { }
//virtual ~ZooAnimal();
virtual std::ostream& print(std::ostream&) const;
// accessors
std::string getName() const { return Name; }
std::string getFamilyName() const { return FamilyName; }
bool getOnExhibition() const { return OnExhibition; }
// ...
protected:
std::string Name;
bool OnExhibition;
std::string FamilyName;
// ...
private:
};
std::ostream& ZooAnimal::print(std::ostream &out) const {
return out << "I am printing ZooAnimal" << std:: endl;
}
#endif
void Endangered::highlight() const {
std::cout << "HIGHLIGHT: HEY, I AM IN DANGER" << std::endl;
}
std::ostream& Endangered::print( std::ostream &out ) const {
// thsi would be fine
// return out << "I Aa Printing Endangered" << std::endl;
out << "I Aa Printing Endangered" << std::endl;
return out;
}
#endif
// Bear
#ifndef BEAR
#define BEAR
#include "ZooAnimal.h"
#include <iostream>
class Bear : public ZooAnimal {
enum DanceType { two_left_feet, macarena, fandango, waltz };
public:
Bear();
//listing all arguments
// passing BaseClass constructor in initialiser list
Bear(std::string name, bool onExhibit=true,
std::string family = "Bear"):
ZooAnimal(name, onExhibit, family),
ival(0), dancetype(macarena) { }
virtual std::ostream& print(std::ostream&) const;
void dance() const;
//virtual ~Bear();
private:
int ival;
DanceType dancetype;
};
#endif
std::ostream& Bear::print(std::ostream &out) const {
return out << "I am printing Bear" << std:: endl;
}
// panda
#ifndef PANDA
#define PANDA
#include <iostream>
#include "Bear.h"
#include"Endangered.h"
class Panda : public Bear, public Endangered {
public:
Panda();
Panda(std::string name, bool onExhibit=true);
// virtual ~Panda();
// mentioning virtual would not be necessary
virtual std::ostream& print(std::ostream&) const;
// mentioning virtual would not be necessary
virtual void highlight() const {
std::cout << "HIGHLIGHT: Hey I am Panda" <<std::endl;
}
};
std::ostream& Panda::print(std::ostream &out ) const {
// this would be fine
// return out << " I am printing Pandaa" << std::endl;
out << "I am printing Panda" << std::endl;
return out;
}
Panda::Panda(std::string name, bool onExhibit)
: Bear(name, onExhibit, "Panda") { }
void Bear::dance() const {
switch(dancetype) {
case two_left_feet:
std::cout << "I am doing two_left_feet"<< std::endl;
break;
case macarena:
std::cout << "I am doing macarena"<< std::endl;
break;
case fandango:
std::cout << "I am doing fandango"<< std::endl;
break;
case waltz:
std::cout << "I am doing waltz"<< std::endl;
break;
}
}
# endif
// mian
#include "Bear.h"
#include "Panda.h"
#include "ZooAnimal.h"
#include<iostream>
#include<string>
int main () {
Endangered a;
ZooAnimal b("John", true, "DiMonte");
//b.print(std::cout);
Bear c("Luigi");
c.dance();
c.print(std::cout);
Panda d("Luigi");
d.print(std::cout);
d.highlight();
d.dance();
Panda e();
}
In main.cpp you firstly included Bear.h and this file contains definition of std::ostream& Bear::print(std::ostream &out). This definition is not guarded by
#ifndef BEAR
#define BEAR
...
#endif
Second include in main is Panda.h and in Panda.h you once again include Bear.h. And because you don't guard Bear::print it is included second time and compiler fails because it doesn't know which method definition it should use.
To reduce occurrence of such errors you should include only declaration in your *.h files while all definitions should go to *.cpp
Ok the stupid answer is that you need to get rid of
//#include "Bear.h" in Panda.
so my question is now
- why?
- why dont I need to include #include "Bear.h" as Bear is part of my inheritance hierarchy? I thought the compiler needed to see the definition.