Feeds:
Posts
Comments

Archive for September, 2004

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 :-)

Read Full Post »

I was working on some code and encountered an annoying problem with generics in C++/CLI. See the following code :-

generic<typename T> where T:Base ref class Test
{
public:
    Test()
    {
        T t = gcnew T(); // won't compile
        t->Hello();
    }
};

It won’t compile :-(

You get this error message :-

C3227: 'T' : cannot use 'gcnew' to allocate a generic type

Crap! That’s what I say! You can’t do much with generics if you cannot instantiate a generic type parameter. Luckily there is a work around (Thanks to Ben Schwehn) :-

generic<typename T> where T:Base ref class Test
{
public:
    Test()
    {
        T t = Activator::CreateInstance<T>();
        t->Hello();
    }
};

You just use the generic overload of Activator::CreateInstance. Cool huh? :nerd:

Read Full Post »

Tracking References

The last couple of blog entries I made were on native C++ references and I thought maybe it’s a good time to talk about tracking references in C++/CLI. The punctuator used to specify a tracking reference is % (similar to & for a native reference). See the code snippet below :-

void ChangeString(String^ str)
{
    str = "String has been changed";
}

void _tmain()
{
    String^ str = "Hello World";
    ChangeString(str);
    Console::WriteLine(str);
}

The output will show that the function didn’t really change the string the way we intended it to. Now modify the ChangeString function as follows :-

void ChangeString(String^% str)
{
    str = "String has been changed";
}

Okay, now it works as expected. For C# folks, this is similar to what happens when you use the ref keyword for function arguments.

Read Full Post »

Follow

Get every new post delivered to your Inbox.