简体   繁体   English

如何将整数“指针”从C#传递到托管CLI C ++

[英]How to pass an integer “pointer” from C# to managed CLI C++

This should be easy (and it is in C++) but I cannot find the right syntax to perform the following task: 这应该很容易(并且在C ++中),但是我找不到正确的语法来执行以下任务:

  1. In C# I have an integer 'result' that I want to pass to a managed C++ function. 在C#中,我具有要传递给托管C ++函数的整数“结果”。
  2. In the managed C++ function I set the value 'result' to say, 6. 在托管C ++函数中,我将值“结果”设置为6。
  3. When the function returns, I have the set value in C# now as 6. 函数返回时,我现在在C#中将设置值设为6。

(The code segment I copy in using the enter code tool above is so ugly I can't warrant its use.) (我使用上面的输入代码工具复制的代码段非常丑陋,我不能保证使用它。)

In C++ all I need is to use an integer pointer, pass the pointer to the function, have the function set it, and then I have the set value in the caller. 在C ++中,我所需要做的就是使用整数指针,将指针传递给函数,对函数进行设置,然后在调用者中获取设置值。 I would really appreciate it if someone could write a little code snippet in C# that takes an integer and somehow passes it as a pointer by boxing or whatever to a managed function and have the managed function set the value so the C# caller has the value on return (but not as a return value). 如果有人可以用C#编写一个带整数的小代码段,并通过装箱或以其他方式将其作为指针传递给托管函数,并让托管函数设置该值,以便C#调用者将其值设置为on,则我将不胜感激。返回(但不作为返回值)。 Matching the syntaxes in the C# world with the analog in the managed C++ world is half the battle. 将C#世界中的语法与托管C ++世界中的模拟语法相匹配是成功的一半。

I can't even figure out a good way to word this question in a google search. 我什至不知道在Google搜索中用这个词表达这个问题的好方法。

Simply pass the argument by reference: 只需通过引用传递参数:

public ref class Example {
public:
    static void Foo(int% arg) {
        arg = 42;
    }
};

Then you call it from C# with: 然后,您可以使用以下命令从C#调用它:

int value;
Example.Foo(ref value);

And don't forget that you can return a value from a method as well. 并且不要忘记,您也可以从方法中返回值。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM