I have a structure as follows
struct _name{
void* person[3];
}name;
I tried to copy elements into a python array but it didn't work.
How do you want to use the bound result? There is no such thing a a void* in Python, unless perhaps if you want to work with capsules, so the easiest to work with is a properly sized integer type, which can subsequently be handed to ctypes, rebound, etc.
In cppyy, I do the exactly that. Example:
import cppyy
cppyy.cppdef("""
typedef struct _name{
void* person[3];
} name;
""")
n = cppyy.gbl.name()
print(n.person[0])
which prints whatever the first pointer points to (it's uninitialized in this example) as an integer address, and cppyy.bind_object() allows rebinding of the pointer to a proxy.
To do the same in pybind11, you can for example do:
#include <pybind11/pybind11.h>
#include <pybind11/pytypes.h>
#include <pybind11/numpy.h>
typedef struct _name {
void* person[3];
} name;
PYBIND11_MODULE(name, m)
{
pybind11::class_<name>(m, "name", pybind11::buffer_protocol())
.def(pybind11::init<>())
.def_property("person", [](name &n) -> pybind11::array {
auto dtype = pybind11::dtype(pybind11::format_descriptor<uintptr_t>::format());
auto base = pybind11::array(dtype, {3}, {sizeof(uintptr_t)});
return pybind11::array(
dtype, {3}, {sizeof(uintptr_t)}, n.person, base);
}, [](name& n) {});
}
which gives you a numpy array of the proper integer type and length. Example use:
>>> import name
>>> n = name.name()
>>> n.person
array([0, 0, 0], dtype=uint64)
>>>
where again the values happen to be what they are, as they're uninitialized w/o a constructor for the struct _name.
Related
I have an structure in c as follows
typedef struct _person{
int id[10];
int number[10];
}person;
How can one bind this using pybind11?
There does not seem to be a pretty way AFAICT when you want the data to be writable (it's somewhat less contrived when the data would be readonly). Anyway, the following does the trick, assuming you have numpy installed:
#include <pybind11/pybind11.h>
#include <pybind11/pytypes.h>
#include <pybind11/numpy.h>
typedef struct _person{
int id[10];
int number[10];
} person;
PYBIND11_MODULE(person, m)
{
pybind11::class_<person>(m, "person", pybind11::buffer_protocol())
.def(pybind11::init<>())
.def_property("id", [](person &p) -> pybind11::array {
auto dtype = pybind11::dtype(pybind11::format_descriptor<int>::format());
auto base = pybind11::array(dtype, {10}, {sizeof(int)});
return pybind11::array(
dtype, {10}, {sizeof(int)}, p.id, base);
}, [](person& p) {})
.def_property("number", [](person &p) -> pybind11::array {
auto dtype = pybind11::dtype(pybind11::format_descriptor<int>::format());
auto base = pybind11::array(dtype, {10}, {sizeof(int)});
return pybind11::array(dtype, {10}, {sizeof(int)}, p.number, base);
}, [](person& p) {});
}
The ticket is to provide the empty base object which makes the array behave as a view object. Without the base, it makes a copy. You do not need the property setter (that would, if implemented, set the array, not the array items) and could raise an error instead of providing the no-op as I did. Also, if you really have two same-sized arrays, you can use a helper function instead of the lambdas.
The basic problem for binding C builtin arrays is that python does not have a proper array type (there is a basic memory view and the module array, but no true array type), hence you need to get one from somewhere and pybind11 prefers to take the one from numpy as it's the best game in town.
Just to show you an alternative, in cppyy (http://cppyy.org), I took a different tack: it has a low-level array view, which can subsequently be handed to numpy for view or copying as desired, since it implements the full buffer protocol. The advantage here is that it's the python user who can decide on the final use. The disadvantage is that if you're going to use numpy anyway, it's an extra step. But it's also directly usable without numpy installed:
import cppyy
cppyy.cppdef("""
typedef struct _person{
int id[10];
int number[10];
} person;
""")
p = cppyy.gbl.person()
print(len(p.id), p.id)
print(list(p.id))
which produces:
(10, <cppyy.LowLevelView object at 0x105ab33b0>)
[0, 0, 0, 0, 0, 0, 0, 0, 0, 0]
I am trying to implement bigint class in c++, it's not completed yet, i have encountered some errors that i am unable understand.
I have erased all other functions (as they are unnecessary in this case)
and karatsuba is not yet completed (but that should't pose a problem in this case).
In the multiply function (overloaded * ) my compiler gives an error:
passing 'const BigInt' as 'this' argument discards qualifiers [-fpermissive]
at line
ans.a = karatsuba(n,m);
I understand that this would occur when i am trying to change a constant object or object passed to a constant function, in my case i am merely creating a new vector and passing it to karatsuba function.
Removing const from overloded * gets rid of this error.
So,does this mean that a constant function can't change anything at all? (including local variables?)
class BigInt {
typedef long long int ll;
typedef vector<int> vi;
#define p10 1000000000;
#define range 9
vi a;
bool sign;
public:
BigInt operator * (const BigInt &num) const
{
vi n(a.begin(),a.end()),m(num.a.begin(),num.a.end());
BigInt ans;
ans.sign = !(sign ^ num.sign);
while(n.size()<m.size()) n.push_back(0);
while(n.size()>m.size()) m.push_back(0);
ans.a = karatsuba(n,m);
return ans;
}
vi karatsuba(vi a,vi b)
{
int n = a.size();
if(n <= 16)
{
// some code
}
// some code
return a;
}
};
Ok so after googling a bit more, i realized that this pointer is implicitly passed to the oveloaded * and then on to karatsuba (as it is a member function of the class), and as karatsuba is not a constant function, there is no guarantee that it won't change the object contents, hence this error is triggered.
One solution is to declare karatsuba as static, as static member functions don't receive this pointer (they can even be called with out a class object simply using :: operator) , read more about them from here Static data members and member functions.
All that is needed to be changed is :-
static vi karatsuba(vi a,vi b)
{
int n = a.size();
if(n <= 16)
{
// some code
}
// some code
return a;
}
I have command-line plusargs that I want to map to enumerated values.
vsim foo +MY_PLUSARG=BAR
How do I get the string "BAR" to become the enum BAR?
If you are using UVM 1.2 or have access to the library, you may want to use uvm_enum_wrapper class to do the conversion. It is a template class wrapper defined in uvm_globals.svh and you can use it as follows:
typedef enum {BISTRO, COFFEE_SHOP, BAR} places_e;
typedef uvm_enum_wrapper#(places_e) places_wrapper;
places_e place;
places_wrapper::from_name("BAR", place);
Quite like the code you provided in this solution, the wrapper class works by traversing the enum entries and creating an assoc array for a enum[string] map for the given enum (supplied as template parameter). So if you are using UVM 1.2, don't repeat.
The idea behind this solution is to avoid a case statement that hardcodes the members of your enumerated type. You want to be able to change the type in one play.
Let's say you have the following enum:
typedef enum {BISTRO, COFFEE_SHOP, BAR} places_e;
You want your user to be able to type:
vsim top +MEET_PLACE=BAR
Now you want to translate the string "BAR" to the enum 'Bar'.
You can do this:
typedef enum {BISTRO, COFFEE_SHOP, BAR} places_e;
module top;
places_e place_map[string];
function void make_map;
places_e pl;
pl = pl.first();
do begin
place_map[pl.name()]=pl;
pl = pl.next();
end while (pl != pl.first());
endfunction // make_map
function string get_list;
string ss;
places_e pl;
pl = pl.first();
ss = "";
do begin
ss = {ss, " ",pl.name()};
pl = pl.next();
end while (pl != pl.first());
return ss;
endfunction // get_list
initial begin
string place_str;
places_e place;
make_map;
if (!$value$plusargs("MEET_PLACE=%s", place_str)) begin
$display("You must choose a MEET_PLACE");
$finish;
end
if (! place_map.exists(place_str)) begin
$display("You must choose from this list: %s", get_list());
$finish;
end
place = place_map[place_str];
$display("Let's meet at a %s!", place.name());
end // initial begin
endmodule // top
I would like to have a class member function behave like a function pointer. I need this behavior to integrate my own classes into some existing code.
It seems that this may be possible using Boost::function and Boost::bind, but I can't seem to get it working. The following code is a minimal example that I am using to test my implementation. The last line in the main() program is what I would like to be able to do.
Any help is greatly appreciated. I am using g++ and Boost 1.46.
// Includes
#include <boost/shared_ptr.hpp>
#include <boost/function.hpp>
#include <boost/bind.hpp>
#include <stdio.h>
using namespace std;
// Define a pure virtual base class
class Base{
public:
virtual double value(double v, double t) = 0;
};
// Define a derived class
class Derived : public Base{
public:
double value(double v, double t){
return v*t;
}
};
// Main program
int main(){
// A derived class
boost::shared_ptr<Derived> p(new Derived);
// Use class directly
printf("value = %f\n", p->value(100, 1));
// Create a boost::function
boost::function< double (Derived*, double, double) > f;
f = &Derived::value;
printf("f(&A, 100, 2) = %f\n", f(p.get(), 100, 2));
// Use boost::bind
printf("bind f(100,3) = %f\n", boost::bind(&Derived::value, p, _1, _2)(100,3));
// Make a boost::function to the binded operation???
boost::function< double (double, double) > f2;
f2 = boost::bind(&Derived::value, p.get()); // This is wrong
printf("f2(100,4) = %f\n", f2(100,4)); // I want to be able to do this!
}
Based on the documentation (See section "Using bind with pointers to members"), you need to specify that the function has two parameters:
f2=bind(&Derived::value, p.get(), _1, _2);
f2(100, 4); // p.get()->value(100, 4)
I'm currently start using boost::program_options for parsing command line options as well as configuration files.
Is it possible to use own template classes as option arguments? That means, something like
#include <iostream>
#include "boost/program_options.hpp"
namespace po = boost::program_options;
template <typename T>
class MyClass
{
private:
T* m_data;
size_t m_size;
public:
MyClass( size_t size) : m_size(size) { m_data = new T[size]; }
~MyClass() { delete[] m_data; }
T get( size_t i ) { return m_data[i]; }
void set( size_t i, T value ) { m_data[i] = value; }
};
int main (int argc, const char * argv[])
{
po::options_description generic("General options");
generic.add_options() ("myclass", po::value< MyClass<int>(2) >(),
"Read MyClass");
return 0;
}
Trying to compile this I get an Semantic Issue (No matching function for call to 'value'). I guess I need to provide some casting to an generalized type but I have no real idea.
Can anybody help?
Thanks
Aeon512
I wouldn't know if boost::program_options allows the use-case you are trying, but the error you are getting is because your are trying to pass an object as a template type to po::value<>. If the size is known at compile-time, you could have the size be passed in as a template parameter.
template< typename T, size_t size >
class MyClass {
T m_data[size];
public:
// ...
};
And then use it like so:
po::value< MyClass<int, 2> >()
You should also look into using Boost.Array instead that I guess fulfills what you are trying to implement.
I would write it like this:
MyClass<int> mine(2);
generic.add_options() ("myclass", po::value(&mine), "Read MyClass");
Then all that needs to be done is to define an input stream operator like this:
std::istream& operator >>(std::istream& source, MyClass& target);
Then Boost Program Options will invoke this stream operator when the myclass option is used, and your object will be automatically populated according to that operator's implementation, rather than having to later call one of the Program Options functions to extract the value.
If you don't prefer the above syntax, something like should work too:
generic.add_options() ("myclass", po::value<MyClass<int> >()->default_value(MyClass<int>(2)), "Read MyClass");
This way you would be creating the instance of your class directly with your desired constructor argument outside of the template part where runtime behavior isn't allowed. I do not prefer this way because it's verbose and you end up needing to call more functions later to convert the value.