Function Arguments - Reference to a Value type?

R

Rich

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.
 
T

Tom Porterfield

Rich said:
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?

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.
 

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