3

I'm using C++/CLI only to unit test unmanaged C++ code in VS2010. I switched the compiler to /clr and using the unmanaged code from a static library.

I have a simple int property in my test class. I would like to pass that as a const int & to a function in native C++. But it can't compile and I've found out that, it's because you can't mix references like that.

What is the way to do it, I tried to following and it's working, but is there a nicer way?

[TestClass]
public ref class MyTestClass
{
private:
    int _my_property;
public:

    [TestMethod]
    void MyTestMethod()
    {
        MyNativeClass c;
        // c.SomeMethod(_my_property) this doesn't work

        int i = _my__property;
        c.SomeMethod(i) // this works
    }
}
Deduplicator
  • 44,692
  • 7
  • 66
  • 118
sekmet64
  • 1,635
  • 4
  • 19
  • 30
  • In the meantime I've found that I can use C++ style pointers which aren't managed, and that's enough for me. `int *_my_property` – sekmet64 May 21 '11 at 12:15

1 Answers1

4

C++ references are really just syntactic sugare for pointers. A C++ pointer points to a specific point in memory, while CLI references can be freely moved around by the garbage collector. To pass a reference to an object in managed memory to unmanged code, you need to pin the pointer.

More info and sample in another SO question: Convert from C++/CLI pointer to native C++ pointer

Edit 2

I'm removing the additional information, since it is obviously wrong (thanks @Tergiver and @DeadMG for your comments). I'm also making the post community wiki, so feel free to add any additional correct information.

Community
  • 1
  • 1
Anders Abel
  • 67,989
  • 17
  • 150
  • 217
  • 2
    You are correct that a managed reference must be pinned before it can be handed off to unmanaged code. What can be pinned however has nothing to do with the stack. Only "blittable" objects can be pinned. A blittable object is essentially a value type or an array of value types. I'm not clear on all the "blitability rules". – Tergiver May 21 '11 at 14:05
  • References do not move, objects move. Otherwise this explains the OP's problem. – Hans Passant May 21 '11 at 14:50