Reflection on const variables

S

Stabiplan BV

Hi,

I am trying to find const variables outside a class. Thur far I did not
succeed. Without const, the variable is found but with const not.

So, how can I get hold on global const variables using reflection?

Regards,

Rob

// reflection.cpp : main project file.

#include "stdafx.h"

using namespace System;
using namespace System::Reflection;

const int test = 10023;

int main(array<System::String ^> ^args)
{
Module^ mod = Assembly::GetExecutingAssembly()->GetModules()[0];
Console::WriteLine( mod->Name );
FieldInfo^ info = mod->GetField("test",
BindingFlags::public|
BindingFlags::NonPublic|
BindingFlags::Instance|
BindingFlags::Static|
BindingFlags::FlattenHierarchy);
if ( info ) {
Console::WriteLine( "Found: " + info->Name );
}
array<Type^>^t = mod->FindTypes( Module::FilterTypeName, "t*" );
for( int i = 0; i < t->Length; i++ ) {
Console::WriteLine( t->Name );
}
Console::ReadLine();
return 0;
}
 
B

Ben Voigt

Stabiplan BV said:
Hi,

I am trying to find const variables outside a class. Thur far I did not
succeed. Without const, the variable is found but with const not.

So, how can I get hold on global const variables using reflection?

Global const variables by default have static scope, and are optimized away
by the compiler. Try explicitly adding a prototype declaring the variable
as extern.
Regards,

Rob

// reflection.cpp : main project file.

#include "stdafx.h"

using namespace System;
using namespace System::Reflection;

const int test = 10023;

Try:
extern const int test;
const int test = 10023;
int main(array<System::String ^> ^args)
{
Module^ mod = Assembly::GetExecutingAssembly()->GetModules()[0];
Console::WriteLine( mod->Name );
FieldInfo^ info = mod->GetField("test",
BindingFlags::public|
BindingFlags::NonPublic|
BindingFlags::Instance|
BindingFlags::Static|
BindingFlags::FlattenHierarchy);
if ( info ) {
Console::WriteLine( "Found: " + info->Name );
}
array<Type^>^t = mod->FindTypes( Module::FilterTypeName, "t*" );
for( int i = 0; i < t->Length; i++ ) {
Console::WriteLine( t->Name );
}
Console::ReadLine();
return 0;
}
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Similar Threads


Top