I want to give a c++ function a custom symbol name (without mangling) so that a can call it from c directly without redirection. For example: If I have the following class in c++:
class Foo {
public:
Foo();
void some_method(int);
int a_;
};
I want to give Foo::some_method a custom name like Foo_some_method so that I can call it from c code directly without need for redirection from another function inside extern "C", is that possible?
No, to enable a C conpatible calling convention and symbol name you need to produce an extern "C" normal function (in theory, an extern "C" function pointer could also work).
So write your glue code.
It is plausible with reflection you'll be able to automate that. But that is not yet standardized, and covid 19 may delay it past 2023.
I tested this using g++ and gcc and it worked! I used asm labels to give the symbol a custom name.
product.h
#ifndef BCC702_PRODUTO_H
#define BCC702_PRODUTO_H
#include <string>
#include <ostream>
class product {
public:
/// Create product
product(int id, double price, char* name);
/// Print product
void print() asm("Asm_product_print");
void set_name(char* name) asm("Asm_product_set_name") ;
private:
int id_;
double price_;
char* name_;
};
#endif //BCC702_PRODUTO_H
product.cpp compiled to object using g++
#include "product.h"
#include <iostream>
void product::print() {
std::cout << name_ << std::endl;
}
product::product(int id_, double price_, char* _name_) :
id_(id_), price_(price_), name_(_name_) {}
void product::set_name (char* _name_) {
product::name_ = _name_;
}
main.c compiled with gcc
typedef struct{
int id_;
double price_;
char* name_;
} product;
void Asm_product_set_name(product* p, char* string);
void Asm_product_print(product* p);
char* example = "hello world!";
int main(){
product p;
Asm_product_set_name(&p, example);
Asm_product_print(&p);
return 0;
}
Finally, link objects using g++. And the test result is:
Hello world!
However, I'm not sure whether it will work with other c++ compilers.
Related
I am working through this problem I found on Git to brush up on some skills. Using friend is prohibited. C++ styling should be used compared to C.
Essentially, I cannot call the identify() function that belongs to the Brain member variable in my Human class. It just will not let me access it. If you can code this up, and explain where I am going wrong, that would be great.
Create a Brain class, with whatever you think befits a brain. It will have an Identify() function that returns a string containing the brain's address in memory, in hex format, prefixed by 0x.
Then, make a Human class, that has a constant Brain attribute with the same lifetime. It has an identify() function, that just calls the identity() function of its Brain and returns its result.
Now, make it so this code compiles and displays two identical addresses:
int main(){
Human bob;
std::cout << bob.identify() << "\n";
std::cout << bob.getBrain().identify() << "\n";
}
Here is what I have so far:
#pragma once
#include "Brain.h"
class Human
{
const Brain humanBrain;
public:
Human();
std::string identify();
};
#include "Human.h"
#include <iostream>
#include <string>
#include <sstream>
Human::Human()
{
this->humanBrain = new Brain;
}
std::string Human::identify()
{
Brain b = this->humanBrain.identify(); // This is essentially what I am trying to call--and I can't access it.
const Brain * ptr = humanBrain;
std::ostringstream test;
test << ptr;
return test.str();
}
#pragma once
#include <string>
#include <iostream>
class Brain
{
int age;
std::string gender;
void* ptr;
public:
Brain();
//std::string getBrain();
const std::string identify();
void setPtr(void* p);
};
#include "Brain.h"
#include <iostream>
#include <sstream>
Brain::Brain()
{
age = 10;
gender = "male";
}
const std::string Brain::identify()
{
//const Brain* bPtr = &this;
const Brain* bPtr = this;
ptr = this;
std::ostringstream test;
test << &bPtr;
std::string output = "Brain Identify: 0x" + test.str();
return output;
}
Your Human::humanBrain member is declared as type const Brain, which is correct per the instructions, however your Brain::identify() method is not qualified as const, so you can't call it on any const Brain object. This is the root of the problem that you are having trouble with.
In addition, there are many other problems with your code, as well:
Human::humanBrain is not a pointer, so using new to construct it is wrong. And, you don't need a pointer to get the address of a variable anyway. Nor do you actually need a pointer to the member at all in this project.
Human lacks a getBrain() method, so bob.getBrain() in main() will not compile, per the instructions.
Human::identify() is calling humanBrain.identify(), which returns a std::string as it should, but is then assigning that string to a local Brain variable, which is wrong (not to mention, you are not even using that variable for anything afterwards). The instructions clearly state that Human::identity() should simply call Brain::identify() and return its result, but you are not doing that.
Brain::identify() is printing the address of its local variable bPtr rather than printing the address of the Brain object that identify() is begin called on, per the instructions.
With all of that said, try something more like this instead:
Human.h
#pragma once
#include "Brain.h"
#include <string>
class Human
{
const Brain humanBrain;
public:
Human() = default;
std::string identify() const;
const Brain& getBrain() const;
};
Human.cpp
#include "Human.h"
std::string Human::identify() const
{
return humanBrain.identity();
}
const Brain& Human::getBrain() const
{
return humanBrain;
}
Brain.h
#pragma once
#include <string>
class Brain
{
int age;
std::string gender;
public:
Brain();
std::string identify() const;
};
Brain.cpp
#include "Brain.h"
#include <sstream>
Brain::Brain()
{
age = 10;
gender = "male";
}
std::string Brain::identify() const
{
std::ostringstream test;
test << "Brain Identify: 0x" << this;
return test.str();
}
I have been looking in different threads with this error which is quite common but it feels like the IDE I am using messed with my workspace and I can't quite find the problem. I am setting up an extremely basic class called "Movie" that is specified below:
Movie.hpp :
#ifndef MOVIE_HPP
#define MOVIE_HPP
#include <iostream>
#include <string>
using std::string, std::cout,std::size_t;
class Movie
{
private:
std::string name;
std::string rating;
int watched_ctr;
public:
Movie(const string& name, const string& rating, int watched_ctr);
~Movie();
//getters
string get_name() const;
string get_rating() const;
int get_watched() const;
//setters
void set_name(string name);
void set_rating(string rating);
void set_watched(int watched_ctr);
};
#endif // MOVIE_HPP
Movie.cpp:
#include <iostream>
#include <string>
#include "Movie.hpp"
using std::string, std::cout,std::size_t,std::endl;
Movie::Movie(const string& name, const string& rating, int watched_ctr)
: name(name) , rating(rating) , watched_ctr(watched_ctr) {
}
Movie::~Movie()
{
cout << "Destructor for Movies class called /n";
}
//Getters
string Movie::get_name(){return name;}
string Movie::get_rating(){return rating;}
string Movie::get_watched(){return watched_ctr;}
//Setters
void Movie::set_name(std::string n){this -> name = n;}
void Movie::set_rating(std::string rating){this -> rating = rating;}
void Movie::set_watched(int ctr){this -> watched_ctr = ctr;}
The main.cpp I am trying only consists in creating one Movie object:
#include <iostream>
#include <string>
#include "Movie.hpp"
using std::string, std::cout,std::size_t,std::endl;
int main()
{
Movie StarTrek("Star Trek", "G", 20);
}
As you can see, I set all the attribute to private in order to exercise with the set/get methods but I keep stumbling upon the same error on each of them stating >"C:/Users/.../ProjectsAndTests/MoviesClass/Movie.cpp:18:8: error: no declaration matches 'std::__cxx11::string Movie::get_name()"
if you could give me a hint on what might cause this error I would greatly appreciate thank you!
I tried opening another workspace with classes implemented inside of them and the syntax I am using is very close from this test workspace I opened which compiled fine (no error regarding declaration match).
There are 2 problems with your code.
First while defining the member functions outside class you're not using the const. So to solve this problem we must use const when defining the member function outside the class.
Second, the member function Movie::get_watched() is declared with the return type of string but while defining that member function you're using the return type int. To solve this, change the return type while defining the member function to match the return type in the declaration.
//----------------------vvvvv--------->added const
string Movie::get_name()const
{
return name;
}
string Movie::get_rating()const
{
return rating;
}
vvv------------------------------>changed return type to int
int Movie::get_watched()const
{
return watched_ctr;
}
Working demo
**On my main i can't add a note on my new Object of the Class Trabalho
ass.add_nota(num);
**
There is a error on my compilation.
My "Trabalho.h" code:
#include <string>
#include <vector>
#include <iostream>
//#include "Enunciado.h"
//#include "Pessoa.h"
using namespace std;
class Estudante;
class Enunciado;
template <class T>
class Trabalho{
static int id_auxiliar;
string texto;
int ano;
int id;
vector<float> calif;
T* Enun;
vector<Estudante*> estudantes;
vector<Enunciado*> enunciados;
public:
Trabalho();
Trabalho(string texto, vector<Estudante*> est, T* en, int ano);
~Trabalho();
void set_texto(string texto);
string get_texto();
void add_nota(float nota);
void add_enun(Enunciado* en){Enun = en;};
int get_id(){return id;};
int get_ano() {return ano;};
void reutilizar(int id_enun);
vector<float> get_calif() {return calif;};
vector<Estudante*> get_estudantes() {return estudantes;};
Enunciado* get_enunciado() {return Enun;};
};
#endif
And my main code:
int main(int argc, char const *argv[]) {
int n;
int m;
Pesquisa ah();
float num = 1.1;
Trabalho<Pesquisa> ass();
Trabalho<Pesquisa>* tass = new Trabalho<Pesquisa>();
ass.add_nota(num);
tass->add_nota(num);
#ifndef ENUNCIADO_H_
#define ENUNCIADO_H_
#include "trabalho.h"
#include "Pessoa.h"
#include <string>
using namespace std;
class Enunciado
{
static unsigned int id_auxiliar;
const unsigned int id;
string titulo;
string descricao;
vector<int> anos_utilizados;
static unsigned int max_util;
public:
Enunciado(string titulo, string descricao);
virtual ~Enunciado();
int get_id(){return id;};
void set_titulo(string titulo);
string get_titulo();
void set_descricao(string descricao);
string get_descricao();
vector<int> get_anos_utilizados();
void mod_max_util(int a);
};
class Pesquisa: public Enunciado{
vector<string> ref;
public:
Pesquisa(string tit, string des, vector<string> refe);
};
class Analise: public Enunciado{
vector<string> repositorios;
public:
Analise(string tit, string des, vector<string> repos);
};
class Desenvolvimento: public Enunciado{
public:
Desenvolvimento(string tit, string des);
};
#endif
Both ways when i create a new Trabalho when i define my type (pesquisa is a class type on #include "Enunciado.h".
This is the two erros that appears:
"Description Resource Path Location Type
request for member 'add_nota' in 'ass', which is of non-class type 'Trabalho()' Test.cpp /Trabalho1/src line 42 C/C++ Problem
"
And:
Description Resource Path Location Type
Method 'add_nota' could not be resolved Test.cpp /Trabalho1/src line 42 Semantic Error
Can anyone help?
Thank you !
Your error is in trying to call the default constructor as
Pesquisa ah();
or
Trabalho<Pesquisa> ass();
Unfortunately, C++ is very misleading in this and it would declare your variable ass of type Trabalho<Pesquisa>(), which means "a function of zero arguments returning Trabalho<Pesquisa>" and that's exactly that the compiler error says: a function type is not a class type and as such does not have the member add_nota. Indeed, it does look exactly like a function declaration, if you look at it that way:
int main();
^ ^ ^
type arguments
name
It's a very common mistake, especially for those coming from a Java background. But it can easily catch a C++ programmer off guard as well. More information can be found here or here or here, you can see that the same error message has perplexed a good many people.
If you have a compiler conforming to the C++11 language revision, try replacing all those occurrences by
Trabalho<Pesquisa> ass{};
If not, just leave
Trabalho<Pesquisa> ass;
Unlike in Java, this does not mean that the variable will stay uninitialized. It's the C++ way to call a default (zero-argument) constructor.
I have these two files table.cpp and table.h in my program code apart from the main.cpp. The files are described as below
table.cpp
#include <iostream>
#include "table.h"
using namespace std;
// accessor function for Name
char* PeriodicTable::Name()
{
return Name;
}
// accessor function for Symbol
char* PeriodicTable::Symbol()
{
return Symbol;
}
table.h
#ifndef TABLE_H
#define TABLE_H
class PeriodicTable
{
char Name[15], Symbol[3], GroupName[20], Block, State[25], Colour[15], Classification[20];
int GroupNo, AtomicNo, PeriodNo;
float Weight;
public:
char* Name();
char* Symbol();
};
#endif
but the problem is that the IntelliSense(since I am using Visual C++ Express 2010) shows a red curved underline below the name and symbol in the accessor function in table.cpp. I can't understand why???
Your member functions and member variables have the same name. This is not possible in C++. That's why various conventions exist for naming member variables, e.g. m_name, name_ etc. (NB: When dealing with underscores in identifiers make sure you don't use a reserved name by accident.)
You might wonder why and how that could possibly go wrong. In your example there clearly is no way to invoke operator() on char[15], but the problem is that the compiler only knows that after performing semantic analysis. There could also be cases where it is impossible to disambiguate. For example:
struct Func {
void operator()() { };
};
struct C {
Func f;
void f() {}
};
int main() {
C c;
c.f(); // which one?
}
SOLVED: http://pastebin.com/seEaALZh
I was trying to create simple items system, where i can get item information by its id. I cant use array, because items ids are lets say random. I want to use declared items as variables and i want to quickly find any item info by its id. The only way i found is stl map.
So I have this simple code:
main.h
#include <iostream>
#include <map>
enum
{
weapon,
ammo
};
class c_items
{
bool operator()(const c_items& l, const c_items& r) const
{
return (l.id < r.id);
}
public:
c_items(void){};
c_items(int id, char name[], int type);
char *name;
int type;
int id;
};
extern std::map<int,c_items> Stuff;
c_items::c_items(int id, char name[], int type) : id(id), type(type), name(name)
{
Stuff[id] = c_items(id, name, type);
}
const c_items
brass_knuckles (546, "Brass knuckles", weapon),
golf_club (2165, "Gold club", weapon);
main.cpp
#include "main.h"
std::map<int,c_items> Stuff;
using namespace std;
int main()
{
// cout << Stuff[2165].name.data();
return 1;
}
And for some reason program crashes. How to correctly insert class data into map on class initialization?
The problem is order of initialization. The static constructors for brass_knuckles and golf_club run first, before the static constructor for Stuff, so they attempt to insert into a map that is not yet constructed.
In addition, you NEVER want variable DEFINITIONS in a header file, since if you include the header file in multiple source files, you end up with multiple definitions, which will at best cause a link failure. So you should move the DEFINITIONS out of the .h file and into the .cpp file. Putting them AFTER the definition of Stuff will fix the order of initialization problem.
You can have a DECLARATION of the variables in the header file if you want to use them in other compilation units:
extern const c_items brass_knuckles, golf_club;
you cannot put c_item in Stuff like that
instead
std::map<int,c_items> Stuff = { {item1.id, item1}, {item2.id, item2}};
but you also need to all the recommendation made by #Chris Dodd
so
c_items::c_items(int id, char name[], int type) : id(id), type(type), name(name)
{}
extern const c_items brass_knuckles, golf_club;
and in the main.cpp
const c_items brass_knuckles = {546, "Brass knuckles", weapon);
const c_items golf_club = (2165, "Gold club", weapon);
std::map<int,c_items> Stuff = { {brass_knuckles.id, brass_knuckles}, etc....};