Native C++ cpp file:
#include "stdafx.h"
#include <iostream>
int strcpyTest(int dest, int *sour)
{
int s = dest + 10;
std::cout << "s" << s << std::endl;
std::cout << "&s" << &s << std::endl;
sour = &s;
int x = *sour + 20;
std::cout << "sour" << sour << std::endl;
std::cout << "*sour" << *sour << std::endl;
return x;
}
C++/CLI h file:
#pragma once
using namespace System;
using namespace System::Runtime::InteropServices;
namespace SubFunction {
public ref class Test
{
public:
int StrTest(int d);
int xxx;
};
}
C++/CLI cpp file:
#include "stdafx.h"
#include "CPlusPlus.h"
#include "SubFunction.h"
int SubFunction::Test::StrTest(int d)
{
int x;
int dd = strcpyTest(d, &x);
xxx = x;
return dd;
}
C# cs file:
int a = 15;
Test ts = new Test();
int x = ts.StrTest(a);
int y = ts.xxx;
MessageBox.Show(x.ToString());
MessageBox.Show(y.ToString());
In the final MessageBox, "xxx" is a pointer address. For the first time, "xxx" has a pointer address value. If it is calculated again, it always appears 0. Why? I don't understand. How to get the value? Or get the value of "sour"?
Try setting *sour = s;
then you will see that the value of 'x' has changed inside 'StrTest()' and you'll get the behavior that you are expecting that 'x' will have the value of 's'.
When you set sour = &s;
as in your example here, you are changing the address that the local pointer 'sour' is pointing to, and there's no way that 'StrTest()' will know about it, since it's a local copy of the pointer you passed in.
By using '*sour = s' you're changing the value of the variable that it points to which is 'x'.
You can think of it like this the local pointer 'sour' is a local copy and is constructed and only accessible to 'strcpyTest()' and is destroyed when it runs out of scope, however it contains the reference of 'x' that you passed in such that if you dereference the local pointer 'sour' you can modify the value of x.
Illustration:
Inside
int strcpyTest(int dest, int *sour)
Note: This is not a valid syntax, it's just for illustration purpose.
sour ----> [&x] // Contains the address of variable 'x' passed in by 'StrTest()'
*sour ----> [x] // Fetches the value of variable 'x' (Dereferences 'sour' to access the value of 'x')
sour = (Address) // Sets a new address to 'sour', which means it no longer points to '&x' that you passed in from 'StrTest()'
*sour = (Value) // Still points to '&x' from 'StrTest()', and assigns a new value to it
Wether you pass in '&x' or you construct a pointer and pass it to the function 'strcpyTest()', then you'll find that 'sour' will be a local copy of that pointer.
Side note: If you have a data structure that's not small, then what i suggest you do is to return a pointer to it from strcpyTest() instead of returning the actual value so that you avoid copying the data unnecessarily, other than that it's perfectly fine to set *sour = s;
.