boost.python Avoid registering inner class twice but still expose in python - boost-python

I have some C++ data structures where a templated outer struct has an internal struct. Depending on the template parameter the internal structs may or may not be the same type. When I expose the structures to python using boost.python I want to be able to refer to the inner classes as Outer.Inner. In my boost.python exposing code I should only expose each distinct inner type once. I can query the boost.python registry to avoid exposing the same inner class more than once but what should I do to make a previously exposed inner class an attribute of its outer class? The question might be clearer given this stripped down example:
#include <boost/python.hpp>
struct inner {
};
template< typename T >
struct outer {
typedef inner inner_t;
static const char * name();
static
void expose() {
using namespace boost::python;
class_< outer< T > > outer_class( name() );
// check if inner type is in registry already
const type_info inner_info = boost::python::type_id< inner_t >();
const converter::registration * inner_registration
= boost::python::converter::registry::query( inner_info );
if( inner_registration == 0 || inner_registration->m_to_python == 0 ) {
// not already in registry
scope outer_scope( outer_class );
class_< inner_t > inner_class( "Inner" );
} else {
// already in registry because exposed via different outer
// what to put here? In python we need Outer.Inner to exist
}
}
};
template<>
const char *
outer< int >::name() { return "IntOuter"; }
template<>
const char *
outer< double >::name() { return "DoubleOuter"; }
BOOST_PYTHON_MODULE( inner_classes )
{
outer< int >::expose();
outer< double >::expose();
}
Here's the python code that I would like to run:
import inner_classes as IC
IC.IntOuter.Inner
IC.DoubleOuter.Inner
For completeness here's a Jamroot to compile the above:
import python ;
use-project boost : $(BOOST_ROOT) ;
project : requirements <library>/boost/python//boost_python ;
python-extension inner_classes : inner-classes.cpp ;
install install
: inner_classes
: <install-dependencies>on <install-type>SHARED_LIB <install-type>PYTHON_EXTENSION
<location>.
;
local rule run-test ( test-name : sources + )
{
import testing ;
testing.make-test run-pyd : $(sources) : : $(test-name) ;
}
run-test test : inner_classes test_inner_classes.py ;

Turns out it is quite straightforward once you know how as is the usual case with boost.python. In python this worked:
IC.DoubleOuter.Inner = IC.IntOuter.Inner
but wasn't the solution I was looking for. In C++ this works:
scope outer_scope( outer_class );
outer_scope.attr( "Inner" ) = handle<>( inner_registration->m_class_object );
which I had already tried but hadn't realised that I needed to wrap the class object in a handle<>.

Related

ghidra: how to get static variables using ghidra python api?

I have a following c code (from a benchmark):
int main(int argc, char *argv[])
{
static char buf[10] = "";
/* OK */
buf[9] = 'A';
return 0;
}
I am using ghidra api to get some information out of the binary (precompiled using flag -g). I want to get the variables defined in the function (or globally).
function.getStackFrame().getStackVariables()
gives me variables defined within the function, but it doesn't detect buf, as it is defined as static. From ghidra gui I was able to see that the variables is defined in the "main" under namespaces.
Is there way to get these type of variables (or global variables in general)?
If you compile with gcc, a static variable defined within a function (e.g., the variable buf, in your case) is represented as a global variable that starts with the same name and ends with a compiler-assigned numeric suffix. Such a variable will be assigned within Ghidra to the "global" namespace, rather than the function's namespace.
In Ghidra, each default global variable name ends with the variable's address. Each default local variable name starts with "local_" and ends with the variable's stack offset.
I've only used the Java API. But the Ghidra class hierarchy should be the same, regardless of whether you use Java or Python. Here is an example Java script that will list all non-default global and local variables in the current program:
// Lists non-default global and local variables in the current program.
//#category Example
import ghidra.app.script.GhidraScript;
import ghidra.program.database.ProgramDB;
import ghidra.program.database.symbol.NamespaceManager;
import ghidra.program.database.symbol.SymbolManager;
import ghidra.program.model.listing.Function;
import ghidra.program.model.listing.Variable;
import ghidra.program.model.symbol.Symbol;
import ghidra.program.model.symbol.SymbolType;
public class ListVariables extends GhidraScript {
#Override
public void run() throws Exception {
// List globals
SymbolManager smgr = (SymbolManager)currentProgram.getSymbolTable();
NamespaceManager nmgr =
((ProgramDB)currentProgram).getNamespaceManager();
for (Symbol sym : smgr.getSymbols(nmgr.getGlobalNamespace())) {
if (monitor.isCancelled()) return;
if (sym.getSymbolType() == SymbolType.LABEL) {
String sname = sym.getName();
if (!sname.endsWith(sym.getAddress().toString())) {
printf("global : %s\n", sname);
}
}
}
//List local variables
for (Function func :
currentProgram.getFunctionManager().getFunctions(true)) {
for (Variable var : func.getLocalVariables()) {
if (monitor.isCancelled()) return;
String vname = var.getName();
if (!vname.startsWith("local_")) {
printf("%s : %s\n", func.getName(), vname);
}
}
}
}
}
The script writes its output to the Ghidra console window. Double-clicking a function or variable name in the Ghidra console window will jump the listing to the corresponding function/variable.

Accessing Fantom class' members from a member function in a constructor it-block?

If I define this Fantom class
const class Mixed
{
const Int whole
const Int numerator
const Int denominator
const | -> Int[]| convertToFrac
new make( |This| func ) { func( this ) }
}
And I want to create an instance defining the convertToFrac function, like this:
class Example
{
Void main( Str args )
{
mixed := Mixed {
whole = 2
numerator = 3
denominator = 8
convertToFrac = |->Int[]| {
return [ whole * denominator + numerator, denominator ]
}
}
}
}
The compiler complains saying:
Unknown variable 'numerator'
Unknown variable 'denominator'
Unknown variable 'whole'
Is there any way to refer to the object "mixed" being created from within the function "convertToFrac", also being defined, without passing the "mixed" object as a parameter of the function?
If I prepend each variable with "mixed", like so:
return [ mixed.whole * mixed.denominator + mixed.numerator, mixed.denominator ]
The compiler complains: Unknown variable 'mixed'.
Using this.whole doesn't make sense as it refers to the Example class.
Using it.whole doesn't make sense either as it refers to the Function.
Can anyone please suggest the way to access the "mixed" object from within the "convertToFrac" function?
As you correctly assessed, the issue is that you're using an it-block inside an it-block, and because you're using an implicit it (i.e. you're don't have any it qualifiers) there is confusion as to what's being referenced.
I'll write out the it qualifiers out long hand so you can see what's going on:
mixed := Mixed {
// 'it' is the Mixed instance
it.whole = 2
it.numerator = 3
it.denominator = 8
it.convertToFrac = |->Int[]| {
// 'it' is now the func param
// 'it.whole' doesn't exist, because there is no func param
return [ it.whole * it.denominator + it.numerator, it.denominator ]
}
}
Your idea of using the mixed variable qualifier was a good one but, unfortunately, whilst processing the ctor the mixed variable hasn't been created yet so can't be referenced.
But you can create your own mixed variable in the it-block, and the following compiles and runs quite happily:
mixed := Mixed {
// 'mixed' doesn't exist here yet, because we're still creating a value to assign to it
it.whole = 2
it.numerator = 3
it.denominator = 8
// assign `it` to our own `mixed` variable
mixed := it
it.convertToFrac = |->Int[]| {
// use our own `mixed` variable
return [ mixed.whole * mixed.denominator + mixed.numerator, mixed.denominator ]
}
}

Shall I build a destructor in this classes?

I am currently working on building an ABM model using C++.
I have classes that have the need to interact with each other, because e.g. class B needs to examine values in class A and return some evaluation on it, which then class C might want to read. Classes need not to change other classes values, only to read from them.
Class B in my current implementation has a po
inter to a vector containing all members of Class A. The pointer is there for two order of reason: it makes easier to initialize the vector, and the vector is left in the scope of main so that I can access and loop over it, calling the members of class A for each agent.
My MCVE:
#include <iostream>
#include <vector>
using namespace std;
class A; // Forward declaration
class B{
int id,
some_value;
vector<A> * A_vec;
public:
// Overloaded constructor
B(int ID, vector<A> & PTR)
{
A_vec = & PTR;
id = ID;
some_value = 0;
};
// Copy Constructor
B( const B& that ):
id(that.id),
some_value(that.some_value)
{
// Pointer ??
};
// Non-default destructor -> uncomment leads to seg_fault
/*
~B(){ delete [] A_vec;};
*/
// Assignment operator
B& operator=(const B& that)
{
id = that.id;
some_value = that.some_value;
// Pointer ??
return *this;
};
//Methods to update different variables go here ..
void do_stuff();
};
class A{
B & class2_ref;
vector<double> o;
public:
int stuff;
// Overloaded constructor
A(int STUFF, B & REF, vector<double> O):
class2_ref(REF),
o(O)
{
stuff = STUFF;
};
// Methods to update different variables go here ..
};
void B::do_stuff()
{
int L = A_vec->size();
for(int l = 0; l<L; l++) some_value += (*A_vec)[l].stuff; // Perform some operation
};
int main(){
int I = 5; // Number of objects of A
vector<double> O(12,2); // Some numbers in here
B b(0,A_vec);
for(int i = 0; i< I; i++)
{
A a(i,b,O);
A_vec.push_back(a);
}
b.do_stuff();
cout<< "Debugging MCVE" << endl;
return 0;
}
My question then is:
Should I implement the destructor/copy constructor/assignment operator in class B? What about class A ? If so, can you please point me to the correct syntax(for the destructor the one above in comments leads to seg fault).
My understanding is that this might be one of the case in which I am happy with a "shallow" destruction of the pointer, because both class B and vector<A> will go out of scope at the return statement. class B owns the pointer, which gets destructed when it is due, and the same for vector.
But then, what about the other member from the rule of three?
There is only one object of class B planned, but I might (small chance) want to generalize later on.
if a class have a pointer type, you should implement a destructor, and i would suggest implementing a copy and an assignment operator as well, else you will be dealing with the same object from 2 different places, which could cause you some errors, for example -
void someFunction(B &b)
{
B a = b;
}
B b(0,A_vec);
someFunction(b); //After finishing someFunction, it will try to delete the vector from a , but it is the same vector you used in b.
b.do_stuff(); // Would cause a seg error
And for the destructor syntax, just delete the vector, not its content, it will use the vector default destrctor on the content:
delete A_vec
just make sure you dont use it if its not initialized, i would suggest just building a empty vector on each ctor of the class, that way you wont get a seg fault and you can use delete.

Inheritance with templates

#include<iostream>
using namespace std;
class C
{
public:
C (){};
virtual void nothing()=0;
virtual ~C (){};
};
class A : public C
{
public:
A (){};
virtual void nothing(){};
};
class B:public A
{
public:
B(){};
void nothing(){};
};
template <class T>
void hi(T){
cout << " i am something\n";
}
template <>
void hi<A>(A)
{
cout << " I am A\n";
}
template <>
void hi<B>(B)
{
cout << " I am B\n";
}
int main ( )
{
C *array [] = {new A,new B};
hi (*array [0]);
hi (*array [1]);
delete array [0];
delete array [1];
return 0;
}
Out:
i am something
I am something
Currently I am writing a program that has to deal with
Inherited types and specialised templates. In the example above I would l would like to see
I am A
I am B
Is there a way to properly invoke the functions corresponding to the objects although I am handling a base class array? I am not sure if type checking and conversion via dynamic_cast is the most elegant solution. Note that this is just an excerpt from a larger program.
Thank you in advance
In the main routine, the three lines shown below create an array of C*.
So any element of that array is treated as a C* regardless of
what the actual type of the element is.
That is, when you pass *array [0] to the function hi(),
the function that gets called is hi(C) which resolves to
the generic hi function, not either of the specialized functions.
C *array [] = {new A,new B};
hi (*array [0]);
hi (*array [1]);
In order to make hi<A> be invoked, you either have to store the pointer
to the new object in a variable of type A* or you need to cast the
C* to an A*.
In a case like this, a virtual function of C, overridden in A and B,
may serve the purpose better.

Nested Class Causing Problems with Templating

For my Data Structures class we've been asked to take a previously implemented balanced tree(from a prior project) and use it to implement parts of the C++ standard map class.
http://cplusplus.com/reference/stl/map/
I figured the most obvious first step was to template the entire class, allowing for separate key and storage types. Of course, I ran into problems with templating. Generally my templating works until I attempt to template a function that is using a local nested datatype "rbNode". If I include template parameters in the function definition, I get syntax errors. If I leave them out, I get "template parameters not included" errors.
This is the class implementation that gives me the errors in Visual Studio 2010 (errors listed below):
#include <cstdlib>
#include <iostream>
template <class key_type, class T>
class myMap
{
private:
//typedef pair<const key_type, T> value_type;
struct rbNode
{
//value_type ref;
int element;
rbNode * left;
rbNode * right;
bool red;
rbNode(int key)
{
left = NULL;
right = NULL;
//ref.first = key;
//ref.second = element;
element = key;
red = true;
}
};
rbNode * root;
bool search(int , rbNode *);
rbNode * LL_Rotation(rbNode *);
};
template <class key_type, class T>
myMap<key_type,T>::rbNode* myMap<key_type,T>::LL_Rotation(rbNode * curr) // errors occur on this line
{
rbNode * temp = curr->right;
curr->right = temp->left;
temp->left = curr;
curr->red = 1;
temp->red = 0;
return temp;
}
This function, however, compiles just fine with the above function commented out:
template <class key_type,class T>
bool myMap<key_type,T>::search(int key,rbNode * tree)
{
if(tree!=NULL)
if(tree->element==key)
return true;
else
if(key< tree->element)
return search(key,tree->left);
else
return search(key,tree->right);
else
return false;
}
In particular, I'm getting
missing ';' before '*'
and
missing type specifier - int assumed. Note: C++ does not support default-int
on the line the implementation for "LLRotation"'s name is in (pointed out in comment). I'm not very experienced with templating, so I get the feeling the I'm making a very stupid mistake. Regardless, if you need more of my code, or more information, let me know. Any help is greatly appreciated.
Note: I'm sure my code has plenty of bad practices, etc. in it. I'm still learning. Feel free to point them out, but I'm mostly concerned with the templating issues.
You're just missing a typename for the dependent name:
template <class key_type, class T>
typename myMap<key_type,T>::rbNode* myMap<key_type,T>::LL_Rotation(rbNode * curr)
^^^^^^^^