Re: String to fixed buffer (and vice versa)
- From: "Willy Denoyette [MVP]" <willy.denoyette@xxxxxxxxxx>
- Date: Wed, 12 Mar 2008 13:04:45 +0100
"LPeter" <LPeter@xxxxxxxxxxxxxxxxxxxxxxxxx> wrote in message news:8106CD7F-764E-4E05-9109-1514C2B7327D@xxxxxxxxxxxxxxxx
"Willy Denoyette [MVP]" wrote:
"LPeter" <LPeter@xxxxxxxxxxxxxxxxxxxxxxxxx> wrote in message
news:55443BCB-190D-4EA1-8339-A13C16B679F7@xxxxxxxxxxxxxxxx
>
> Hi,
>
> I would copy the characters of a string variable to a fixed character
> buffer
> in a struct (and vice versa) in C#.
>
> public struct S
> {
> ...
> public fixed char cBuff[16];
> ...
> }
>
>
> I tried to do this many way, but I often get the following compiler > error:
> "error CS1666: You cannot use fixed size buffers contained in unfixed
> expressions"
>
> What is the simplest way to do this?
> Thanks for any help.
>
> LPeter
>
>
Here is one possible way to do this:
const int len = 16;
internal struct SomeStruct
{
internal unsafe fixed char ca[len];
}
....
SomeStruct someStruct = new SomeStruct ();
string s = "Hello";
char *pca = someStruct.ba;
// make sure your string fits in the fixed array!!!!!!
//....
foreach(char ch in s)
{
*pca++ = ch;
}
// reverse action
pca = c.ba;
string s = new String(pca, 0, len);
But the real question for you to answer is - why do I need fixed buffer?,
there is likely no good answer to it ....
Willy.
Thanks, Willy.
1.
You made a fair a question.
I am working on a small device project with Compact Framework.
I have a native (unmanaged) .dll written in C++.
I have to fill and give some simple unsafe structure to this dll (I can not
bypass this way now).
Of course, I don't use fixed character buffer the other (managed) places in
project.
You don't need to declare your char[] as a "fixed" buffer in a structure that will be passed to unmanaged code, you can declare a char array like this:
[MarshalAs(UnmanagedType.ByValArray, SizeConst = 16)].
public char[] cBuff;
the interop marshaler will embed the char array when passing the structure to unmanaged.
2.
Your solution seems to good but I wouldn't have thought that this is the
simplest way to copy from string to a fixed buffer. I am little disappointed.
Why the dissapointment? When opting for "fixed" buffers, you are dealing with pointers, just like you would in native C. But again, you don't have to use fixed and unsafe.
Willy.
.
- References:
- Re: String to fixed buffer (and vice versa)
- From: Willy Denoyette [MVP]
- Re: String to fixed buffer (and vice versa)
- From: LPeter
- Re: String to fixed buffer (and vice versa)
- Prev by Date: Re: Transaction when using smo and DataContext of linq
- Next by Date: Re: Retrieving items from a List<t>
- Previous by thread: Re: String to fixed buffer (and vice versa)
- Next by thread: Retrieving items from a List<t>
- Index(es):
Relevant Pages
|