Here’s some sample code showing how you can do this; the example calls System::String::InternalLength which is private.
Console::WriteLine(safe_cast<int>(
__typeof(String)->InvokeMember("InternalLength",
BindingFlags::InvokeMethod |
BindingFlags::NonPublic | BindingFlags::Instance,
nullptr,gcnew String("hello world"),
gcnew array<Object^>(0))));
Of course, in the above case what we did is not particularly useful since we could simply have used the Length property which internally calls InternalLength, but it’s just to show how it’s done π
Hey Nish,
C# code seems to be too simple and readable π
Console.WriteLine(typeof(String).InvokeMember("InternalLength", BindingFlags.InvokeMethod | BindingFlags.NonPublic | BindingFlags.Instance, null, "hello world", null));>>the example calls System::String::InternalLength which is private
private ? what about security ?
Hello Vladimir
Access-modifier based security has no impact on Refelction.
>>Access-modifier based security has no impact on Refelction
hm, how can i secure my code in managed appl ?
in unmanaged appl (binary) to invoke some method is not so easy, as it seams.
in managed one even can generate il code into assembly, or maybe override some method\property – a good ‘platform’ for creating viruses… isn’t so ?
Vlad, signing your .NET assembly can ensure your executable is the original; any tampering will change the key, which the CLR will recognize as changed, giving you security when you need it. π
I must agree with the comment.
C# code seems to be too simple and readable
π
Disagree with the C# comment. It is the style of original writing that is the cause for the confusion. Here is a modified C++/CLI statement of the same. π
Console::WriteLine(String::typeid->InvokeMember(“InternalLength”, BindingFlags::InvokeMethod | BindingFlags::NonPublic | BindingFlags::Instance, nullptr, “hello world”, nullptr));
IMHO, the syntax is much the same in C++/CLI or C#, with the added power that is omnipresent in C++, whenever you need it.