Another noob question for you all . . .
I have functions written in C++ that I want to call from C#. I need to
be able to pass a reference to a value type (like an int) so that the
function can change the value - just like passing a pointer to an int
in good old unmanaged C.
Here is the function in C++ (member of testclass) - this compiles to a
DLL without error in C++:
int test_function(int arg1, int^ arg2)
{
int result;
// arg1 is a VALUE type passed IN to the function. The
// function can use the value but not change it.
// arg2 is a REFERENCE to a value type, so the function
// should be able to use the value and change the value.
result = arg1 + *arg2;
*arg2 = 1234;
return( result );
}
I use the DLL from C# so I can call the function.
Here is what I am doing in C# (doesn't compile):
int status, val1, val2;
val1 = 11;
val2 = 12;
status = testclass.test_function(val1, ref val2); //
Chokes on "ref arg2"
The error says - Argument '2': cannot convert from 'ref int' to
'System.ValueType'.
I'm sure I'm doing something fundamentally wrong here. Can someone
here set me straight?
Thanks.
Tom Porterfield - 13 Nov 2006 18:16 GMT
> I have functions written in C++ that I want to call from C#. I need to
> be able to pass a reference to a value type (like an int) so that the
[quoted text clipped - 35 lines]
> I'm sure I'm doing something fundamentally wrong here. Can someone
> here set me straight?
If you want to pass this as a reference from C# to C++, the define your C++
method as follows:
int test_function(int arg1, int % arg2)
{
int result;
result = arg1 + arg2;
arg2 = 1234;
return (result);
}
^ tells managed C++ you want a handle to an object on the GC heap. % tells
managed C++ you want a tracking reference.

Signature
Tom Porterfield
Rich - 13 Nov 2006 18:51 GMT
Perfect - you hit the nail on the head! That solved the problem -
Thanks!
Tom Porterfield - 13 Nov 2006 19:17 GMT
> Perfect - you hit the nail on the head! That solved the problem -
> Thanks!
Glad to help.

Signature
Tom Porterfield