The function is defined in the C# project as:
[DllImport("Project2.dll", CallingConvention = CallingConvention.Cdecl)]
static extern void modifyVar(ref int x);
And the function call is:
modifyVar(ref a)
where a = 4
The native C++ function definition is as follows:
extern "C" _declspec(dllexport) void modifyVar(int* a)
{
int x = 1;
a = &x;
}
Why in the C# project, a is not pointing to the new variable with value 1 after the function call? It still remains 4.
However, if i modify the C++ function to this, it works fine:
extern "C" _declspec(dllexport) void modifyVar(int* a)
{
int x = 1;
*a = x;
}
But, how do I get it to point to a new memory location rather than modifying the value?
Does it having something to do with using IntPtr rather than ref int?
So, as I understand the question, you are asking how to return the address of a variable in the native module. Do it like this:
Note that the variable whose address is returned is not a local variable. It cannot be the address of a local variable because the scope of the local variable ends when the function returns.
And from C# call it like this:
If you'd rather return the pointer through a parameter do it like this:
And from C#:
However, having said all of that, I really doubt that you actually want to return the address of a variable. That global variable doesn't look like it's going to be very useful. And the alternative is heap allocated memory. But then you need to export a deallocator, or allocate off a shared heap. Again, not much fun to be had there. And a pain in the neck too for marshalling.
What is much more likely to be useful is to allocate the variable in the calling code, the managed code, and ask the native code to modify the value of that variable. That makes the lifetime management trivial, and allows you to let the pinvoke marshaller do all the work.