How to use struct or class in function paramers ?

  • Thread starter Thread starter Liren Zhao
  • Start date Start date
L

Liren Zhao

There is a fucntion writen in VC++ in a Dll

something.h

EXTC int WINAPI SendData(char* sendBuf,int sendLen)

And sendBuf is struct in VC++.Can I define a struct or class in C# to call
the function "SendData" ?
 
Liren,

Simply yes, you can use the key word struct to create a class. The
only thing you have to do is specify managed datatypes as follows.

[StructLayout(LayoutKind.Sequential, Pack=1, CharSet=CharSet.Ansi)]
public struct tagRequest
{
// Char[17]
[MarshalAs( UnmanagedType.ByValArray, SizeConst=17 )]
public byte[] abytDateTime;
// byte
public byte bytPriceBreakOn;
/// int
public int bytStoreWideLookup;
}

the above structure will allow c# to fill a memory area the way C++
expects it.
Now you will need to convert a string by using a method like follows:

public static byte[] stob( string item )
{
if ( item == null )
throw( new ArgumentNullException( "item", "String may not be
null." ) );

byte[] iout = new byte[ item.Length ];
for( int i = 0; i < item.Length; i++ )
iout[ i ] = (byte)item[ i ];
return iout;
}

The strings passed must be the length of the desired byte array.

Once the structure is filled just pass it and the length of the
struct. You can get the length of the struct by using the following:

Marshal.SizeOf( typeof( tagRequest ) )

Hope this helps,
Glen Jones MCSD
 

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

Back
Top