I have a C struct and a DLL with a single function. I've used the
MarshalAsAttribute, ref, DLllImport, StructLayout, UnmanagedType, etc...
declarations and I'm not having any luck.
I'm not really clear on when you can use the special declarations for
automatic marshalling or when (or how) you use IntPtr, Marshal.AllocHGlobal,
etc...
Any suggestions on how to translate my C to C# and/or any high-level
feedback on when to use the different approached (especially when the
structures have pointers to other structs or arrays)
Thank you --- Ted
// C
int Populate(int flags,PhotoBuffer *photo);
typedef struct {
byte *buffer;
int bufferSize;
long mode;
} PhotoBuffer
// C#
[DllImport("photo.dll",CharSet=CharSet.Ansi,CallingConvention=CallingConvention.StdCall,SetLastError=true)]
public static extern int populate(int flags, ref aPhotoBuffer);
[StructLayout(LayoutKind.Sequential, CharSet=CharSet.Auto)]
public class PhotoBuffer
{
[MarshalAs(UnmanagedType.LPArray)] public byte[] travBuff;
[MarshalAs(UnmanagedType.I4)] public int bifferSize
[MarshalAs(UnmanagedType.U8)] public long ,mode;
}
PhotoBuffer photo=new PhotoBuffer();
photo.mode=1;
byte[] imageData=new byte[2048];
photo.buffer=imageData;
photo.bufferSize=2048;
int returnCode=Populate(2,ref photo);
>I have a C struct and a DLL with a single function. I've used the
> MarshalAsAttribute, ref, DLllImport, StructLayout, UnmanagedType, etc...
[quoted text clipped - 41 lines]
>
> int returnCode=Populate(2,ref photo);
1. long in C# is 64 bit!
2. You can't marshal array's by reference when contained in a struct or
class, use an IntPtr instead.
Following should do....
[StructLayout(LayoutKind.Sequential)]
struct PhotoBuffer
{
internal IntPtr buffer;
internal int size;
internal int mode;
}
PhotoBuffer pbu = new PhotoBuffer();
pbu.mode = 2;
byte[] bytearr = new byte[10] {60, 61, 62, 63, 64, 65, 66, 67, 68,
69};
pbu.size = bytearr.Length;
GCHandle gcH = GCHandle.Alloc(bytearr); // Allocate a GCHandle for
the managed array
pbu.buffer = Marshal.UnsafeAddrOfPinnedArrayElement(bytearr, 0); //
pin the array and return a pointer to the first element
int returnCode = Populate(2, ref pbu);
gcH.Free(); // Free the buffer
Willy.
TedSharp - 29 Mar 2005 04:29 GMT
Willy ---
Thanks, it worked. So , I did "Explicit" allocated of out-of-CLR memory and
are using IntPtr.
Your long = 64 bit comment made me search some comphrehensive info covering
C <-> C# datatype sizes. I found this link
http://msdn.microsoft.com/library/default.asp?url=/library/en-us/vcmxspec/html/v
cmg_PlatformInvocationServices.asp
--- Ted
> >I have a C struct and a DLL with a single function. I've used the
> > MarshalAsAttribute, ref, DLllImport, StructLayout, UnmanagedType, etc...
[quoted text clipped - 69 lines]
>
> Willy.