Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Pass int by reference from C++/CLI to C#

Tags:

c#

c++-cli

It seems like there must be a duplicate question, but I haven't been able to find it.

I'm writing a bridge to let an old C program access some C# objects. The bridge is written in C++/CLI.

In one case there is a C# function that's defined as:

public static string GetNameAndValue(out int value);

My C++/CLI wrapper function:

char* GetNameAndValue(int* value);

Which is easy enough to call from C. But how do I call the C# method from C++/CLI?

I first tried the obvious:

String ^ str;
str = TheObject::GetNameAndValue(value);

That gives me error C2664: Cannot convert parameter 2 from 'int *' to 'int %'.

Okay, then, how about GetNameAndValue(%value)? That gives me error C3071: operator '%' can only be applied to an instance of a ref class or a value-type.

Fair enough. So if I create an int I can pass it with %??

int foo;
str = TheObject::GetNameAndValue(%ix);

No dice. C3071 again. Which I find odd because int definitely is a value-type. Or is it?

There must be some magic combination of %, ^, &, or some other obscenity that will do what I want, but after swearing at this thing for 30 minutes I'm stumped. And searching Google for different combinations of C++/CLI and C# mostly gives information about how to call C++ from C#.

SO, my question: How do you pass an int from C++/CLI to a C# method that expects an out int (or ref int, if I have to)?

like image 844
Jim Mischel Avatar asked May 12 '14 21:05

Jim Mischel


2 Answers

C#:

class MyClass 
{ 
    public static string GetNameAndValue(out int value);
}

C++/CLI:

int value;
String^ x = MyClass::GetNameAndValue(value);

C++/CLI wrapper:

CString GetNameAndValue(int* value)
{
    String^ x = MyClass::GetNameAndValue(*value);
    return CString(x);
}

C++/CLI wrapper 2:

CString GetNameAndValue(int& value)
{
    String^ x = MyClass::GetNameAndValue(value);
    return CString(x);
}

It's the same for C# "ref".

like image 125
Tomasz Malik Avatar answered Sep 28 '22 14:09

Tomasz Malik


I know this is answered already but only to clarify what the compiler was suggesting with "C2664: Cannot convert parameter 2 from 'int *' to 'int %'".
I think it wanted this(C++/CLI):

int a=5
int% foo=a;
str = TheObject::GetNameAndValue(foo);
like image 34
Pifcnt Avatar answered Sep 28 '22 13:09

Pifcnt