C -> C# Marshaling / IntPtr - any help?

G

Guest

Hi there,

I had some problems converting C -> C#.

C codes:

unsigned char BYTE;
unsigned short puint8;

typedef struct {
BYTE ValueIn[255];
BYTE ValueOut[255];
} STestA;

typedef struct {
int somevalue;
puint8 ValueIn;
puint8 ValueOut;
} STestB;

typedef STestB *PSTestB;

EXTERN int WINAPI PushCommand(int somevar, PSTestB mypstestb)
{
STestA mySTestA;

memset(mySTestA.ValueIn, 0x00, 256);
memset(mySTestA.ValueOut, 0x00, 256);

if (something)
{
memcpy(mySTestA.ValueIn, mypstestb.ValueIn, sizeofValueIn);
}
}

Okay, i try to convert to c#.

C# codes:

public const int STRLEN = 256;

[StructLayout(LayoutKind.Sequential, CharSet=CharSet.Ansi)]
public struct STestA
{
[MarshalAs(UnmanagedType.ByValArray, SizeConst=STRLEN)]
public byte[] ValueIn;

[MarshalAs(UnmanagedType.ByValArray, SizeConst=STRLEN)]
public byte[] ValueOut;
}

[StructLayout(LayoutKind.Sequential, CharSet=CharSet.Ansi)]
public struct STestB
{
public int somevalue;
public IntPtr ValueIn;
public IntPtr ValueOut;

public STestB(int a)
{
this.somevalue = a;
this.ValueIn =
Marshal.AllocHGlobal(Marshal.SizeOf(typeof(System.UInt16)));
this.ValueOut =
Marshal.AllocHGlobal(Marshal.SizeOf(typeof(System.UInt16)));
}
}

public int PushCommand(int somevar, STestB myTestB)
{
STestA myTestA = new STestA();
myTestB = new STestB(0);

// ignore memset, coz i had allocated 256 spaces in the structure

if (something)
{
// how do i copy the values (short) from IntPtr to byte[] ?
// i know you can do this, to read..
// e.g ushort x;
// x = (ushort)Marshal.ReadInt16(Structure.Data);
}
}

Any help please? Am i on the right track doing this? The most important how
do i do memory copy in C#?

Thanks.
 
R

richlm

In C# you might find the "System.Buffer" class useful for manipulating byte
arrays.

As for "best practices" you are going to have to do an awful lot of work
marshalling data between C & C# - as you have already discovered.

I would suggest you try to 'decouple' your managed code in C# and your
unmanaged code in C/C++ as much as possible.
Perhaps you could build a managed C++ wrapper in VS.NET, in which you do all
that horrible data conversion, and keep your C# "clean" managed code.

If you have the C source code, is compiling it in VS.NET C++ an option?
That'll make things easier.

I've never tried anything like this, these are just some ideas that may be
worth considering. Hope it helps.

Richard.
 

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