Edward
Edward

Reputation: 235

Pass by Reference from C#, Through C.L.I. to Unmanaged C++

I've seen a number of articles on this subject but none have helped me solve my issue. In essence, I want to be able to pass a variable by reference from C#, through a C.L.I. wrapper to a C++ library, modify the variable, and have it passed back up through the functions without using the return value.

The code I currently have is as follows:

In C#:

[DllImport("UtilitiesWrapper.dll", EntryPoint = "Increment", CallingConvention = CallingConvention.Cdecl)]
public static extern void _Increment(int number);

int value;
_Increment( value);

In the C.L.I. wrapper:

extern "C" {
    __declspec( dllexport) void __cdecl Increment( int& number);
};

void __cdecl Increment( int& number) {
    NS_UtilitiesLib::Increment( number);
}

In C++:

namespace NS_UtilitiesLib {
    static void Increment( int& number) {
        ++number;
    }
}

It keeps giving me an error about memory being corrupt at the end of the C.L.I. function which I presume is because it can't understand how to put the C# variable into the parameter (as when I step through the C.L.I. it never picks up the original value). I have tried using [MarshalAs(UnmanagedType.I4)] when declaring the function in C# with DllImport but it still doesn't work.

Does anyone know how to make this work?

Upvotes: 1

Views: 5320

Answers (1)

ta.speot.is
ta.speot.is

Reputation: 27214

I used Google to find this:

[DllImport("ImportDLL.dll")]
public static extern void MyFunction(ref myInteger);

Presumably the author intended ref int myInteger but the point stands: use the ref keyword.

Upvotes: 1

Related Questions