如何在C ++ / CLI中获取指针的值?

时间:2018-09-29 12:49:08

标签: .net c++-cli

本地C ++ cpp文件:

#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文件:

#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文件:

#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文件:

int a = 15;
Test ts = new Test();
int x = ts.StrTest(a);
int y = ts.xxx;
MessageBox.Show(x.ToString());
MessageBox.Show(y.ToString());

在最后一个MessageBox中,“ xxx”是指针地址。第一次,“ xxx”具有指针地址值。如果再次计算,它将始终显示为0。为什么?我不明白如何获得价值?还是获得“酸”的价值?

1 个答案:

答案 0 :(得分:0)

尝试设置*sour = s;,然后您会发现'x'的值在'StrTest()'内已更改,并且您将获得预期的行为,即'x'的值将为' s'。

当您在此处的示例中设置sour = &s;时,您正在更改本地指针'sour'指向的地址,并且'StrTest()'不会知道它,因为您传入的指针的本地副本。

通过使用'* sour = s',您正在更改它所指向的变量'x'的值。

您可以这样看待它:本地指针“ sour”是本地副本,其构造且只能由“ strcpyTest()”访问,并在超出范围时被销毁,但是它包含对“ x”的引用',这样,如果您取消引用本地指针'sour',则可以修改x的值。

插图:

内部

int strcpyTest(int dest, int *sour)

注意:这不是有效的语法,仅用于说明目的。

sour ----> [&x] //包含由'StrTest()'传入的变量'x'的地址
* sour ----> [x] //获取变量'x'的值(取消引用'sour'以访问'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

无论您传入'&x'还是构造一个指针并将其传递给函数'strcpyTest()',您都会发现'sour'将是该指针的本地副本。

侧面说明:如果您的数据结构不小,那么我建议您做的是从strcpyTest()返回指向它的指针,而不是返回实际值,从而避免不必要地复制数据,而不是设置*sour = s;很好。