Yet another marshalling question

K

Keaven Pineau

Hello All,
I am very new to C# since my job consist to design/develop CE drivers but a
client wants to use my C API into a .NET envrironment.

I have 2 functions I would like to get help with.

1- BOOL WriteDataSyncCard (unsigned short Address, unsigned char* pBuffer,
unsigned char* Length);
pBuffer is allocated outside the function and will not modified
Length is a 1 byte length value and can modified in the function with the
actual written number of bytes.

2- BOOL ReadDataSyncCard (unsigned short Address, unsigned char* pBuffer,
unsigned char* Length);
pBuffer is allocated outside the function and will be updated with the data
read from the card
Length is a 1 byte length value and can modified in the function with the
actual read number of bytes.

I have look aroud and found a few informations on what to be done. Here is
what I have done for now.

[DllImport("SyncContactCardAPI.dll")]
private static extern int WriteDataSyncCard(Int16 Address, byte[] pBuffer,
IntPtr Length);

public static int WriteData(Int16 Address, byte[] pBuffer, IntPtr Length)
{
//Do I need to do something with the parameters here since they are only
a pass-throught??
int Status = WriteDataSyncCard(Address, pBuffer, Length);
return Status;
}

[DllImport("SyncContactCardAPI.dll")]
private static extern int ReadDataSyncCard(Int16 Address, IntPtr pBuffer,
IntPtr Length);

public static int ReadData(Int16 Address, out byte[] pBuffer, IntPtr Length)
{
int Offset = 0;
byte BufferSize = //How do I get the 1 byte value pointed by Length??;

IntPtr Data = MemoryManager.AllocHeap((int)BufferSize);

int Status = ReadDataSyncCard(Address, Data, Length);

//Getting actual read size
BufferSize = //How do I get the 1 byte value pointed by Length??;

pBuffer = new byte[io_ProfileSize];
for (uint i = 0; i < BufferSize; i++)
{
pBuffer = Marshal.ReadByte(Data, Offset);
Offset++;
}

MemoryManager.FreeHeap(Data);

return Status;
}

Thank you very much!

Keaven
 
N

Nicholas Paldino [.NET/C# MVP]

Keaven,

You don't need to declare the Length parameters as IntPtrs and then
allocate memory for them. Just declare them as ref byte and then pass them
as such and it will work just fine.

Also, are the unsigned chars strings? If it is, you can declare them as
strings, and pass them directly, instead of doing the conversion yourself.
Just make sure to attach the MarshalAs attribute, setting the UnmanagedType
to UnmanagedType.LPStr.

Finally, if you are using unsigned shorts, then you should use the
ushort type. Int16 is signed.
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Top