From C to unsafe C#

  • Thread starter Thread starter msnews.microsoft.com
  • Start date Start date
M

msnews.microsoft.com

Hi,

I am trying to port some C code to C# but I am stuck on the following lines:

*((unsigned*)&b[3]) = (unsigned)a;
...
((void(*)())&b)();

where a and b are both arrays of type unsigned char (for which I used byte
arrays in C#). I know it needs to be within an unsafe block and use a fixed
statement but I am still not sure on the final details.

Thanks!
 
I believe the first line can simply translated using

*((uint*)&b[3]) = (uint)a;

the second line is a call to a function pointer, you will have to create a
delegate for that.

initialize the delegate with a method "a" like the following:

MethodInvoker method = new MethodInvoker (a);

then you can call it like that:

method();
 
Thanks very much for helping. I ended up with a couple problems, however.

In the original C code a was an unsigned char array. Therefore, when I cast
it to uint as you specify, I end up with a "Cannot convert type error."
Secondly, the & requires a fixed statement, which requires a pointer, but it
doesn't seem to work with arrays so I am not sure what to specify.

On the second line, what is the method name I specify. In my C code I am
not calling a function but accessing a register, the same location specified
by 'b' in the previous line.

Thanks again!

cody said:
I believe the first line can simply translated using

*((uint*)&b[3]) = (uint)a;

the second line is a call to a function pointer, you will have to create a
delegate for that.

initialize the delegate with a method "a" like the following:

MethodInvoker method = new MethodInvoker (a);

then you can call it like that:

method();

msnews.microsoft.com said:
Hi,

I am trying to port some C code to C# but I am stuck on the following
lines:

*((unsigned*)&b[3]) = (unsigned)a;
...
((void(*)())&b)();

where a and b are both arrays of type unsigned char (for which I used byte
arrays in C#). I know it needs to be within an unsafe block and use a
fixed
statement but I am still not sure on the final details.

Thanks!
 

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