1

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.

2
  • 1
    Use ref Commented Apr 27, 2013 at 0:31
  • "Reference parameters", and the similar "output parameters", would be the term for which to Google. Commented Apr 27, 2013 at 0:39

1 Answer 1

2

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.

Sign up to request clarification or add additional context in comments.

1 Comment

Bless you! Worked like a charm. Yes I know I can return a value but in my case I am already returning something else so the position is filled!

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.