473,769 Members | 2,120 Online
Bytes | Software Development & Data Engineering Community
+ Post

Home Posts Topics Members FAQ

byte[] Test2=&Test1[66];

I have another problem, maybe it is simple to fix.

I have this:

byte[] Test=new byte[100];

But I now want to have a second pointer Test2 to point to a location inside
this Test.
But with no copying.
Something like this.
byte[] Test2=&Test[66];

The intentions is that Test2[0] == Test[66]

I need this to find a record position inside a memory block that is a array
of bytes.
And I need this reference to modify the memory directly.

Any idea how to do this?

--
http://www.skyscan.be

Nov 16 '05 #1
5 1603
Hi Olaf,

what are you referring to is called unsafe code in C#. To use it, you need
to compile with the /unsafe compile option and mark the method or class in
which you want to use unsafe constructs as 'unsafe'.

To do exactly what you are saying:

unsafe void Test()
{
byte[] test = new byte[100];

test[66] = 20;

fixed (byte* test2 = &test[66])
{
Console.WriteLi ne("test[66] = {0}, test2[0] = {1}", test[66],
test2[0]);
test2[0] = 100;
Console.WriteLi ne("test[66] = {0}, test2[0] = {1}", test[66],
test2[0]);
}
}

But I would recommend not to use unsafe code unless you really need it.
First, it doesn't necessarily increase performance, as it prevents the
garbage collector from moving the fixed object. Secondly, your code becomes
unverifiable and thus requires full trust to execute. For non performance
critical scenarios, it could be better to write a wrapper class around the
byte array, for example to access bytes with offset (really just an
example):

public class MyWrapper
{
byte[] data;
int offset;

public MyWrapper(byte[] data, int offset)
{
this.data = data;
this.offset = offset;
}

public byte this[int index]
{
get { return data[index + offset]; }
set { data[index + offset] = value; }
}
}

HTH,
Stefan

"Olaf Baeyens" <ol**********@s kyscan.be> wrote in message
news:41******** **************@ news.skynet.be. ..
I have another problem, maybe it is simple to fix.

I have this:

byte[] Test=new byte[100];

But I now want to have a second pointer Test2 to point to a location
inside
this Test.
But with no copying.
Something like this.
byte[] Test2=&Test[66];

The intentions is that Test2[0] == Test[66]

I need this to find a record position inside a memory block that is a
array
of bytes.
And I need this reference to modify the memory directly.

Any idea how to do this?

--
http://www.skyscan.be

Nov 16 '05 #2
"Olaf Baeyens" wrote:
I have another problem, maybe it is simple to fix.

I have this:

byte[] Test=new byte[100];

But I now want to have a second pointer Test2 to point to a location inside
this Test.
But with no copying.
Something like this.
byte[] Test2=&Test[66];

The intentions is that Test2[0] == Test[66]
That is impossible to do in C#.
I need this to find a record position inside a memory block that is a array
of bytes.
And I need this reference to modify the memory directly.

Any idea how to do this?


As you write it, you can use pointers in unsafe code blocks or unsafe methods.

byte[] b = new byte[ 100 ];
unsafe {
fixed( byte* pBuffer = &b[ 66 ] ) {
// ...
}
}

To avoid using "fix"-ed statements, you can use GCHandle to pin arrays and
have a pointer to it.

byte[] b = new byte[ 100 ];
GCHandle hData = GCHandle.Alloc( b, GCHandleType.Pi nned );
try {
unsafe {
byte* pBuffer = ((byte*)hData.A ddrOfPinnedObje ct().ToPointer( )) + 66;
// ...
}
}
finally {
hData.Free();
}

HTH,
Tom.
Nov 16 '05 #3
> what are you referring to is called unsafe code in C#. To use it, you need
to compile with the /unsafe compile option and mark the method or class in
which you want to use unsafe constructs as 'unsafe'.


Well I need this as a function result so that other classes can point to
this series of bytes and process it on their own.
I am porting my C++ code to C# and these are techniques used in the original
C++ classes.

I do realize that the managed way is different than unmanaged.
Below is part of the orignal C++ code that I want to port

assume char *m_pBuffer=new byte[126];

public: BYTE *RecGetRecAt(co nst _int64 aiIndex) {
_int64 iBufferOffset=m _iRecSize*aiInd ex;
BYTE *pPos=m_pBuffer +iBufferOffset;
return pPos;
};

So I was hoping to have something like this in C#:

assume byte[] m_pBuffer=new byte[126];

public byte[] RecGetRecAt(con st _int64 aiIndex) {
_int64 iBufferOffset=m _iRecSize*aiInd ex;
byte [] pPos=m_pBuffer+ iBufferOffset;
return pPos;
};

But I can imaging that the GC will have trouble keeping track of the
m_pBuffer.
The bad news is that it is performance critical.
Nov 16 '05 #4
Olaf,

Instead of passing an array, why not create a collection and pass that
around? Or rather, create a wrapper of some sort that references the
original array, but each wrapper can have a different offset, and when you
perform operations (through the wrapper), it works on the offset, something
like this:

public class ArrayWrapper
{
// The offset.
private int offset;

// The array.
byte[] array;

public ArrayWrapper(by te[] array, int offset)
{
// Store the array and offset.
this.array = array;
this.offset = offset;
}

// This is where the important stuff takes place.
public byte this[int index]
{
get
{
// Get the value, offset by the index.
return array[index + offset];
}
set
{
// Set the value, offset by the index.
array[index + offset] = value;
}
}
}

This would allow you to point to the same array, and have offsets into
the array, and not change the indexes in other areas.

Hope this helps.
--
- Nicholas Paldino [.NET/C# MVP]
- mv*@spam.guard. caspershouse.co m

"Olaf Baeyens" <ol**********@s kyscan.be> wrote in message
news:41******** **************@ news.skynet.be. ..
what are you referring to is called unsafe code in C#. To use it, you
need
to compile with the /unsafe compile option and mark the method or class
in
which you want to use unsafe constructs as 'unsafe'.


Well I need this as a function result so that other classes can point to
this series of bytes and process it on their own.
I am porting my C++ code to C# and these are techniques used in the
original
C++ classes.

I do realize that the managed way is different than unmanaged.
Below is part of the orignal C++ code that I want to port

assume char *m_pBuffer=new byte[126];

public: BYTE *RecGetRecAt(co nst _int64 aiIndex) {
_int64 iBufferOffset=m _iRecSize*aiInd ex;
BYTE *pPos=m_pBuffer +iBufferOffset;
return pPos;
};

So I was hoping to have something like this in C#:

assume byte[] m_pBuffer=new byte[126];

public byte[] RecGetRecAt(con st _int64 aiIndex) {
_int64 iBufferOffset=m _iRecSize*aiInd ex;
byte [] pPos=m_pBuffer+ iBufferOffset;
return pPos;
};

But I can imaging that the GC will have trouble keeping track of the
m_pBuffer.
The bad news is that it is performance critical.

Nov 16 '05 #5
Olaf,

Instead of passing an array, why not create a collection and pass that
around? Or rather, create a wrapper of some sort that references the
original array, but each wrapper can have a different offset, and when you
perform operations (through the wrapper), it works on the offset, something
like this:

public class ArrayWrapper
{
// The offset.
private int offset;

// The array.
byte[] array;

public ArrayWrapper(by te[] array, int offset)
{
// Store the array and offset.
this.array = array;
this.offset = offset;
}

// This is where the important stuff takes place.
public byte this[int index]
{
get
{
// Get the value, offset by the index.
return array[index + offset];
}
set
{
// Set the value, offset by the index.
array[index + offset] = value;
}
}
}

This would allow you to point to the same array, and have offsets into
the array, and not change the indexes in other areas.

Hope this helps.
--
- Nicholas Paldino [.NET/C# MVP]
- mv*@spam.guard. caspershouse.co m

"Olaf Baeyens" <ol**********@s kyscan.be> wrote in message
news:41******** **************@ news.skynet.be. ..
what are you referring to is called unsafe code in C#. To use it, you
need
to compile with the /unsafe compile option and mark the method or class
in
which you want to use unsafe constructs as 'unsafe'.


Well I need this as a function result so that other classes can point to
this series of bytes and process it on their own.
I am porting my C++ code to C# and these are techniques used in the
original
C++ classes.

I do realize that the managed way is different than unmanaged.
Below is part of the orignal C++ code that I want to port

assume char *m_pBuffer=new byte[126];

public: BYTE *RecGetRecAt(co nst _int64 aiIndex) {
_int64 iBufferOffset=m _iRecSize*aiInd ex;
BYTE *pPos=m_pBuffer +iBufferOffset;
return pPos;
};

So I was hoping to have something like this in C#:

assume byte[] m_pBuffer=new byte[126];

public byte[] RecGetRecAt(con st _int64 aiIndex) {
_int64 iBufferOffset=m _iRecSize*aiInd ex;
byte [] pPos=m_pBuffer+ iBufferOffset;
return pPos;
};

But I can imaging that the GC will have trouble keeping track of the
m_pBuffer.
The bad news is that it is performance critical.

Nov 16 '05 #6

This thread has been closed and replies have been disabled. Please start a new discussion.

Similar topics

2
26914
by: David Cook | last post by:
Java's InetAddress class has some methods that use a byte-array to hold what it describes as a 'raw IP address'. So, I assume that they mean an array like: byte ba = new byte; would hold an IPv4 address. Ok, yes, in theory, there are enough bits to hold the values. But, my Java book clearly states that a byte is a SIGNED quantity, is part of the Integer class, and can hold values ranging from 127
13
2163
by: Ray Z | last post by:
So far, I get the idea that if I want to use both the unmanaged and managed memory, I can not avoid memory copy. But I DO need to avoid it. I get a idea that maybe I could use "union" to convert byte to int and so on. Here is my source code, I wonder if this will work with GC? struct MyUnion {
7
6747
by: War Eagle | last post by:
I have two byte arrays and a char (the letter S) I was to concatenate to one byte array. Here is what code I have. I basically want to send this in a one buffer (byte array?) through a socket. SWXXXXXXXXXYYYYZZZZZZZZZZZZZZZZZZZZZ Where S is the command for SEND and should just be the character S. Where W is a byte representing how long the filename (testfile.txt) is. In this case 12. Where XXXXXXX is converted from a string that...
6
2783
by: Dennis | last post by:
I was trying to determine the fastest way to build a byte array from components where the size of the individual components varied depending on the user's input. I tried three classes I built: (1) using redim arrays to add to a normal byte array (2) using an ArrayList and finally (3) using a memorystream. These three classes are listed below the test sub called "TestBuildByteArray". It was interesting that using the memorystream was...
8
4203
by: moondaddy | last post by:
I need to convert a byte array to a string and pass it as a parameter in a URL and then convert it back to the original byte array. However, its getting scrambled in the conversion. In short, here's the code: ====================================== Dim textConverter As New ASCIIEncoding Dim sParam As String = "This is my cool param" Dim bytParam() As Byte 'load the byte array here...
16
3884
by: johannblake | last post by:
I have a variable that is 1 bit wide. I also have a variable that is a byte. I want to shift the bits out of the byte into the bit variable (one at a time) but am not sure how to do this or whether it is even possible. Here is what my code looks like: // data is a variable 1 byte in size while bitVariable is 1 bit in size. i is a byte. for (i = 0; i < 8; i++) {
4
2214
by: Frederick Gotham | last post by:
What do you think of the following code for setting and retrieving the value of bytes in an unsigned integer? The least significant bit has index 0, then the next least significant bit has index 1, and so on. The code computes at runtime the byte-order of the unsigned integer, but alas it would be better if it could be determined at compile-time. The code potentially invokes undefined behaviour if an unsigned integer contains padding bits....
1
4836
by: MimiMi | last post by:
I'm trying to decrypt a byte array in java that was encrypted in C#. I don't get any error messages, just a result that's completely not what I was hoping for. I think I am using the same type of algorithm, initialization vector (IV), mode, padding, key etc, but I just don't get the two languages to "understand each other", or, in other words, I must be missing out on something crucial. I encrypt a byte array in C# and send over the byte...
2
17968
by: MimiMi | last post by:
I'm trying to decrypt a byte array in java that was encrypted in C#. I don't get any error messages, just a result that's completely not what I was hoping for. I think I am using the same type of algorithm, initialization vector (IV), mode, padding, key etc, but I just don't get the two languages to "understand each other", or, in other words, I must be missing out on something crucial. I encrypt a byte array in C# and send over the byte...
10
6380
by: Scott Townsend | last post by:
So I need to talk to a devices that expects all of the bits and bytes I sent it to be in specific places (not yet 100% defined). I wanted to create a structure/class with all of the data in it and then convert that to a byte array, pass it to the device, then get a reply and then convert that to a structure. I'm having issues with making sure what I've coded is correct. Cant figure out how to define an array in structure that is a...
0
9422
by: Hystou | last post by:
Most computers default to English, but sometimes we require a different language, especially when relocating. Forgot to request a specific language before your computer shipped? No problem! You can effortlessly switch the default language on Windows 10 without reinstalling. I'll walk you through it. First, let's disable language synchronization. With a Microsoft account, language settings sync across devices. To prevent any complications,...
0
10208
Oralloy
by: Oralloy | last post by:
Hello folks, I am unable to find appropriate documentation on the type promotion of bit-fields when using the generalised comparison operator "<=>". The problem is that using the GNU compilers, it seems that the internal comparison operator "<=>" tries to promote arguments from unsigned to signed. This is as boiled down as I can make it. Here is my compilation command: g++-12 -std=c++20 -Wnarrowing bit_field.cpp Here is the code in...
1
9987
by: Hystou | last post by:
Overview: Windows 11 and 10 have less user interface control over operating system update behaviour than previous versions of Windows. In Windows 11 and 10, there is no way to turn off the Windows Update option using the Control Panel or Settings app; it automatically checks for updates and installs any it finds, whether you like it or not. For most users, this new feature is actually very convenient. If you want to control the update process,...
0
8867
agi2029
by: agi2029 | last post by:
Let's talk about the concept of autonomous AI software engineers and no-code agents. These AIs are designed to manage the entire lifecycle of a software development project—planning, coding, testing, and deployment—without human intervention. Imagine an AI that can take a project description, break it down, write the code, debug it, and then launch it, all on its own.... Now, this would greatly impact the work of software developers. The idea...
1
7404
isladogs
by: isladogs | last post by:
The next Access Europe User Group meeting will be on Wednesday 1 May 2024 starting at 18:00 UK time (6PM UTC+1) and finishing by 19:30 (7.30PM). In this session, we are pleased to welcome a new presenter, Adolph Dupré who will be discussing some powerful techniques for using class modules. He will explain when you may want to use classes instead of User Defined Types (UDT). For example, to manage the data in unbound forms. Adolph will...
0
6662
by: conductexam | last post by:
I have .net C# application in which I am extracting data from word file and save it in database particularly. To store word all data as it is I am converting the whole word file firstly in HTML and then checking html paragraph one by one. At the time of converting from word file to html my equations which are in the word document file was convert into image. Globals.ThisAddIn.Application.ActiveDocument.Select();...
0
5294
by: TSSRALBI | last post by:
Hello I'm a network technician in training and I need your help. I am currently learning how to create and manage the different types of VPNs and I have a question about LAN-to-LAN VPNs. The last exercise I practiced was to create a LAN-to-LAN VPN between two Pfsense firewalls, by using IPSEC protocols. I succeeded, with both firewalls in the same network. But I'm wondering if it's possible to do the same thing, with 2 Pfsense firewalls...
2
3558
muto222
by: muto222 | last post by:
How can i add a mobile payment intergratation into php mysql website.
3
2812
bsmnconsultancy
by: bsmnconsultancy | last post by:
In today's digital era, a well-designed website is crucial for businesses looking to succeed. Whether you're a small business owner or a large corporation in Toronto, having a strong online presence can significantly impact your brand's success. BSMN Consultancy, a leader in Website Development in Toronto offers valuable insights into creating effective websites that not only look great but also perform exceptionally well. In this comprehensive...

By using Bytes.com and it's services, you agree to our Privacy Policy and Terms of Use.

To disable or enable advertisements and analytics tracking please visit the manage ads & tracking page.