logo
down
shadow

Accessing any structs members at run-time


Accessing any structs members at run-time

Content Index :

Accessing any structs members at run-time
Tag : cpp , By : 22.
Date : January 02 2021, 06:48 AM


Comments
No Comments Right Now !

Boards Message :
You Must Login Or Sign Up to Add Your Comments .

Share : facebook icon twitter icon

Accessing public readonly members of structs in external assemblies


Tag : fhash , By : David
Date : March 29 2020, 07:55 AM
like below fixes the issue Normally when people say 'it looks like a bug in the compiler' that is code for 'I don't know what I'm doing'. In this situation however, it does look to be like a bug.
The F# compiler makes a copy of structs behind the scenes in case they get mutated. (This is why even if you define a struct with mutable fields you must attribute the instance of that struct as mutable before you can update its fields.) It appears that the special magic going on behind the scenes forgets about 'readonly' struct fields.

Accessing struct members and arrays of structs from LLVM IR


Tag : cpp , By : yatil
Date : March 29 2020, 07:55 AM
I hope this helps you . Since the original answer is the correct answer to the "pre-edit" question, I'm writing a completely new answer to the new question (and my guess that the structs are not actually the same was pretty good).
The problem isn't about DataLayout as such [but you will need the DataLayout to solve the problem, so you need to update the code to create the module before starting to make LLVM-IR], but the fact that you are combining a union that has alignment restrictions in a struct with lesser alignment restrictions:
struct S {
    short s;        // Alignment = 2 
    union U {    
        bool b;     // Alignment = 1
        void *v;    // Alignment = 4 or 8
    };
    U u;            // = Alignment = 4 or 8
};
members.push_back( IntegerType::get( ctx, sizeof( short ) * 8 ) );
members.push_back( ArrayType::get( IntegerType::get( ctx, 8 ), sizeof( S::U ) ) );
int main() {
    LLVMContext ctx;

    vector<Type*> members;
    members.push_back( IntegerType::get( ctx, sizeof( short ) * 8 ) );
    members.push_back( PointerType::getUnqual( IntegerType::get( ctx, 8 ) ) );

    StructType *const llvm_S = StructType::create( ctx, "S" );
    llvm_S->setBody( members );

    Module *const module = new Module( "size_test", ctx );
    ExecutionEngine *const exec = createEngine( module );
    DataLayout const *const layout = exec->getDataLayout();
    module->setDataLayout( *layout );

    cout << "sizeof(S) = " << sizeof( S ) << endl;
    cout << "allocSize(S) = " << layout->getTypeAllocSize( llvm_S ) << endl;

    delete exec;
    return 0;
}
Type* MakeUnionType( Module* module, LLVMContext& ctx, vector<Type*> um )
{
    const DataLayout dl( module );
    size_t maxSize = 0;
    size_t maxAlign = 0;
    Type*  maxAlignTy = 0;

    for( auto m : um )
    {
        size_t sz = dl.getTypeAllocSize( m );
        size_t al = dl.getPrefTypeAlignment( m );
        if( sz > maxSize ) 
            maxSize = sz;
        if( al > maxAlign) 
        {
            maxAlign = al;
            maxAlignTy = m;
        }
    }
    vector<Type*> sv = { maxAlignTy };
    size_t mas = dl.getTypeAllocSize( maxAlignTy );
    if( mas < maxSize )
    {
        size_t n = maxSize - mas;
        sv.push_back(ArrayType::get( IntegerType::get( ctx, 8 ), n ) );
    }
    StructType* u = StructType::create( ctx, "U" );
    u->setBody( sv );
    return u;
}

int main() {
    LLVMContext ctx;

    Module *const module = new Module( "size_test", ctx );
    ExecutionEngine *const exec = createEngine( module );
    DataLayout const *const layout = exec->getDataLayout();
    module->setDataLayout( *layout );

    vector<Type*> members;
    members.push_back( IntegerType::get( ctx, sizeof( short ) * 8 ) );
    vector<Type*> unionMembers = { PointerType::getUnqual( IntegerType::get( ctx, 8 ) ), 
                   IntegerType::get( ctx, 1 )  };
    members.push_back( MakeUnionType( module, ctx, unionMembers ) );

    StructType *const llvm_S = StructType::create( ctx, "S" );
    llvm_S->setBody( members );

    cout << "sizeof(S) = " << sizeof( S ) << endl;
    cout << "allocSize(S) = " << layout->getTypeAllocSize( llvm_S ) << endl;

    delete exec;
    return 0;
}

Accessing members of structs in a list in C


Tag : c , By : jaset
Date : March 29 2020, 07:55 AM
like below fixes the issue I have been working through the exercises in K&R on my quest to learn C, and I've hit a strange problem. I wrote a program to count words, characters, and lines in a file, then draw a histogram displaying the count for each. Everything worked well until I tried to make my code a little more reusable with a struct. My struct is as follows: , When you do this:
struct category catList[] = {words, lines, characters};
struct category* createCat(char *name) {
    struct category* cat = (struct category*) malloc(sizeof(struct category));
    //...
    return cat;
}
struct category *catList[] = {&words, &lines, &characters};
catList[i]->count++;

accessing struct members in array like manner: padding in structs different than in arrays?


Tag : cpp , By : Thierry Brunet
Date : March 29 2020, 07:55 AM
this one helps. Suppose I have a structure comprising several members, each being of the same type. I'd like to safely access the members both by name and by an array index, so I introduced a union that comprises the actual struct and an array, which corresponds to the members of the struct in terms of number and type. See the following code, which illustrates how I'd like to "view" the struct in two different ways by using such a union: , Your way is UB, you may instead do something like:
template<typename elemT>
class productData {
    elemT data[4];
public:
    const elemT& operator[](int i) const { return data[i];}
    const elemT& color() const { return data[0]; }
    const elemT& size() const { return data[1]; }
    const elemT& application() const { return data[2]; }
    const elemT& division() const { return data[3]; }

    elemT& operator[](int i) { return data[i];}
    elemT& color() { return data[0]; }
    elemT& size() { return data[1]; }
    elemT& application() { return data[2]; }
    elemT& division() { return data[3]; }
};

How Can I Build A Sequence Of Structs With Integer Members of Increasing Value at Compile Time in C++11


Tag : cpp , By : tommy
Date : March 29 2020, 07:55 AM
will help you Working in an embedded environment, I'm repeatedly writing code that takes an array of bytes from a protocol layer and turns those bytes into a C++ class representation. , It seems you want something like:
template <typename ...Ts>
void f(Ts... args)
{
    const int dummy[] = {0, ((std::cout << std::hex << args << std::endl), 0)...};
    static_cast<void>(dummy); // Avoid warning for unused variable
}

template <std::size_t N, typename Tuple, std::size_t ...Is>
void process(std::array<std::uint8_t, N> const& array, Tuple tuple, std::index_sequence<Is...>)
{
    int i = 0;
    const int dummy[] = {((memcpy(&std::get<Is>(tuple), array.data() + i, sizeof(std::tuple_element_t<Is, Tuple>)), i += sizeof(std::tuple_element_t<Is, Tuple>)), 0)...};
    static_cast<void>(dummy); // Avoid warning for unused variable
    f(std::get<Is>(tuple)...);
}

template <std::size_t N, typename ... Ts>
void process(std::array<std::uint8_t, N> const& array, std::tuple<Ts...> tuple)
{
    process(array, tuple, std::index_sequence_for<Ts...>{});
}
Related Posts Related QUESTIONS :
  • Is it possible to implement a non-owning "slightly smart" pointer on top of standard weak pointers?
  • how to configure the AcquireCredentialsHandleA correctly
  • Using private versions of global extern variables with OpenMP
  • Eigen Block wrong amount of columns and rows
  • Memory alignment rules in inheritance
  • Is nullptr falsy?
  • tm_wday returns a large integer outside 0-6 range
  • Scope a using declaration, inside a header
  • How to specify constructor's template arguments inside a new expression?
  • Sort an array via x86 Assembly (embedded in C++)?? Possible?
  • How to Replace only Part of the Variable using #define
  • How do you compare the performace of valarrays vs built-in arrays?
  • Is it normal for C++ static initialization to appear twice in the same backtrace?
  • c++ generate a good random seed for psudo random number generators
  • Why isn't my operator overloading working properly?
  • Getting meaningful error messages from fstream's in C++
  • C++: Converting Julian dates to Gregorian
  • Could someone explain this interesting behaviour with Sleep(1)?
  • Is it possible to roll a significantly faster version of modf
  • Updating pointer using signals and slots
  • How are classes more secure than structures?
  • finding "distance" between two pixel's colors
  • C++ Greatest Number Verification
  • Why does my token return NULL and how can I fix it?(c++)
  • C++ enforce conditions on inherited classes
  • what happened if an exception is not captured?
  • Redundant naming in C/C++ typedefs/structs
  • question about STL thread-safe and STL debugging
  • killing a separate thread having a socket
  • Returning the size of available virtual memory at run-time in C++
  • Parallel computing for integrals
  • How do I force my std::map to deallocate memory used?
  • C++ Templates: implicit conversion, no matching function for call to ctor
  • Adding python script to c++ project
  • C++ private pointer "leaking"?
  • Initializing Primitive Array to One Value
  • how is push_back implemented in STL vector?
  • C++ Profiling: KiFastSystemCallRet
  • Multiple rows with a single INSERT in SQLServer 2008
  • Use super class's address/pointer in initialization list
  • double fork using vfork
  • Convert char pointer (char*) to struct
  • Does anyone have good tips for using pc-lint?
  • C++ How fast is passing around objects?
  • template type's ctor arguments at instantiation time
  • Get list of windows in taskbar on Windows 7?
  • Curl connection options
  • Best cross-platform solution for network server?
  • simple c++ file opening issue
  • Switching from C++ (with a lot of STL use) to C for interpreter building
  • How can I access the JPEG image pixels as a 3D array like we do in MATLAB?
  • What wording in the C++ standard allows static_cast<non-void-type*>(malloc(N)); to work?
  • Avoid allocating in constructor or preserve simplicity (and RAII?)
  • Can C++ raise an error when std array initialization is too small?
  • Reference to end is ambiguous
  • Problem with basic usage of std::enable_if
  • How to print out a decimal number as octal number using setiosflags in C++
  • Open Visual Studio with solution and specific file and line
  • Enum value based on template type
  • Is there any way to swap nodes in std::list?
  • shadow
    Privacy Policy - Terms - Contact Us © scrbit.com