Pointer to memberfunction for managed code?

F

Frank Vanris

Hi,

I have the following code:

#include "stdafx.h"
#using <mscorlib.dll>

using namespace std;

__gc class A {
public:
A() : _value(0) {}
~A() {}

void setValue(int value) {
_value = value;
}
int getValue() {
return _value;
}

private:
int _value;
};

int _tmain()
{
A* a = new A();
void (A::*func)(int);
func = &A::setValue;

(a->*func)(42);
cout << a->getValue() << endl;
delete a;
return 0;
}


This compiles and runs fine when I declare A to be unmanaged (i.e. without
the __gc), but when I make it managed it gives me the following compile
error:

c:\Frank\Develop\BoostTest\BoostTest.cpp(26): error C2843: 'A' : cannot take
the address of a non-static data member or method of a managed type

which is at the location where I declare the func (so not in the assignment
one line lower).

Does this mean I cannot have pointer to memberfunction for managed code? Or
is there another way I can have a pointer to memberfunction?

Frank.
 
T

Tomas Restrepo \(MVP\)

Frank,
I have the following code:

#include "stdafx.h"
#using <mscorlib.dll>

using namespace std;

__gc class A {
public:
A() : _value(0) {}
~A() {}

void setValue(int value) {
_value = value;
}
int getValue() {
return _value;
}

private:
int _value;
};

int _tmain()
{
A* a = new A();
void (A::*func)(int);
func = &A::setValue;

(a->*func)(42);
cout << a->getValue() << endl;
delete a;
return 0;
}


This compiles and runs fine when I declare A to be unmanaged (i.e. without
the __gc), but when I make it managed it gives me the following compile
error:

c:\Frank\Develop\BoostTest\BoostTest.cpp(26): error C2843: 'A' : cannot take
the address of a non-static data member or method of a managed type

which is at the location where I declare the func (so not in the assignment
one line lower).

Does this mean I cannot have pointer to memberfunction for managed code? Or
is there another way I can have a pointer to memberfunction?

There are delegates for managed code, which are a more clean and the
preferable alternative.

Why do you need a pointer to the member function?
 
F

Frank Vanris

Delegates! I didn't know that. Thanks.

The reason I wanted to use pointer to memberfunction was that I wanted to
use the boost library, especially the bind functions which accept a pointer
to memberfunction.

I will try to use the delegates instead.

Frank.
 

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

Top