在 C# 中将 IntPtr 转换为 int*?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/830832/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-05 03:22:32  来源:igfitidea点击:

Convert IntPtr to int* in C#?

c#pointersintptrmanaged-code

提问by user20493

I have a C++ DLL returning an int*to a C# program. The problem is the int*in C# remains nullafter the assignment.

我有一个 C++ DLL 返回int*一个 C# 程序。问题是int*在 C#null中分配后仍然存在。

When I assign the C++ result to an IntPtr, I get a correct non-null value. However any attempt to convert this to an int*results in null.

当我将 C++ 结果分配给 时IntPtr,我得到一个正确的非空值。然而,任何试图将其转换为一个int*以结果null

I've tried:

我试过了:

IntPtr intp = cppFunction ();           // Non-null.

int* pi = (int *) intp;                 // Results in null.

int* pi = (int *) intp.ToPointer ();    // Results in null.


void* vp = intp.ToPointer ();

int* pi = (int *) vp;                   // Results in null, but vp is non-null.

How can I get a non-null int*?

我怎样才能得到一个非 null int*

Thanks! Alan

谢谢!艾伦

回答by James Black

You cppFunction declaration should be something like:

你的 cppFunction 声明应该是这样的:

void cppFunction(ref int* ptr) {
   ptr = somevalue;
}

That should solve your problem.

那应该可以解决您的问题。

You may find this useful also: http://www.pcreview.co.uk/forums/thread-2902012.php

您可能会发现这也很有用:http: //www.pcreview.co.uk/forums/thread-2902012.php