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

时间:2022-07-10 21:17:10

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

我有一个C ++ DLL将int *返回给C#程序。问题是C#中的int *在赋值后保持为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时,我得到一个正确的非null值。但是,将此转换为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

1 个解决方案

#1


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

#1


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