Search code examples
c#managed

How to pass an integer "pointer" from C# to managed CLI C++


This should be easy (and it is in C++) but I cannot find the right syntax to perform the following task:

  1. In C# I have an integer 'result' that I want to pass to a managed C++ function.
  2. In the managed C++ function I set the value 'result' to say, 6.
  3. When the function returns, I have the set value in C# now as 6.

(The code segment I copy in using the enter code tool above is so ugly I can't warrant its use.)

In C++ all I need is to use an integer pointer, pass the pointer to the function, have the function set it, and then I have the set value in the caller. I would really appreciate it if someone could write a little code snippet in C# that takes an integer and somehow passes it as a pointer by boxing or whatever to a managed function and have the managed function set the value so the C# caller has the value on return (but not as a return value). Matching the syntaxes in the C# world with the analog in the managed C++ world is half the battle.

I can't even figure out a good way to word this question in a google search.


Solution

  • Simply pass the argument by reference:

    public ref class Example {
    public:
        static void Foo(int% arg) {
            arg = 42;
        }
    };
    

    Then you call it from C# with:

    int value = 0;
    Example.Foo(ref value);
    

    And don't forget that you can return a value from a method as well.