Reputation: 2100
I am trying to use pinvoke to marshal a C structure to C#. While I am able to marshal an intptr I cannot find the syntax to marshal a double pointer. Both the int pointer and double pointer are used on the C side to alloc an array of ints or doubles.
Here is the C struct:
struct xyz
{
int *np; // an int pointer works fine
double *foo;
};
And here is the c# class:
[StructLayout(LayoutKind.Sequential, CharSet = CharSet.Ansi)]
public class xyz
{
Intptr np; // works fine
// double *foo ??
}
I am unable to find any instructions on how to marc
Upvotes: 2
Views: 7241
Reputation: 6191
Check out this description for what an IntPtr is. Have you tried using:
[StructLayout(LayoutKind.Sequential, CharSet = CharSet.Ansi)]
public class xyz
{
IntPtr np;
IntPtr foo;
}
Upvotes: 1
Reputation: 612993
You seem to think that IntPtr
is a pointer to an int
. That is not the case. An IntPtr
is an integer that is the same width as a pointer. So IntPtr
is 32 bits wide on x86, and 64 bits wide on x64. The documentation makes all this clear.
The closest equivalent native type to IntPtr
is void*
, an untyped pointer.
So your class in C# should be:
[StructLayout(LayoutKind.Sequential)]
public class xyz
{
IntPtr np;
IntPtr foo;
}
To read the scalar value that np
refers to call Marshal.ReadInt32
. And to write it call Marshal.WriteInt32
. But more likely, since this is a pointer, the pointer refers to an array. In which case you use the appropriate Marshal.Copy
overload to read and write.
For the pointer to double, if the value is a scalar there is no method in Marshal
to read or write the value. But again, it is surely an array in which case use Marshal.Copy
to access the contents.
Upvotes: 0