C# Convert T to long - c#

I have a generic class (C#),
class MyClass<T> where T : struct, IComparable<T>
{
public T filelocation;
}
T can be either UInt32 or UInt64 (nothing else).
I need to convert filelocation to a long to seek in a file...
I have tried the following
long loc = (T)myclass.filelocation;
long loc = (T)(object)myclass.filelocation;
But nothing seems to work...
Any ideas?

Call Convert.ToInt64.
Writing (object)fileLocation creates a boxed UInt32.
Boxed value types can only be unboxed to their original value types, so you cannot cast it in one step to long.
You could write (long)(ulong)fileLocation, but that will fail for a uint for the same reason.

Try Convert.ToInt64.
long loc = Convert.ToInt64(myclass.filelocation);

You may use TryParse:
long lng;
int testNum = 55;
long.TryParse(testNum.ToString(),out lng);

with your class definition if i write something like
public MyClass<long> myclass = new MyClass<long>();
public long returnLong()
{
return myclass.filelocation;
}
myclass.fileLocation return long by defult

Related

Compare byte[] to T

I want to make a list of pointers to locations that contains a certain value in the process memory of another process. The value can be a short, int, long, string, bool or something else.
My idea is to use Generics for this. I have one problem with making it, how can I tell the compiler to what type he needs to convert the byte array?
This is what I made:
public List<IntPtr> ScanProccessFor<T>(T ItemToScanFor)
{
List<IntPtr> Output = new List<IntPtr>();
IntPtr StartOffset = SelectedProcess.MainModule.BaseAddress;
int ScanSize = SelectedProcess.MainModule.ModuleMemorySize;
for (int i = 0; i < ScanSize; i++)
if (ReadMemory(SelectedProcess, StartOffset + i, (UInt16)Marshal.SizeOf(ItemToScanFor)) == ItemToScanFor)
Output.Insert(Output.Count,StartOffset + i);
return Output;
}
How can I tell the compiler that he needs to convert the byte[] to type T?
Your question is a little bit confusing, but I'll try to answer what I can
Instead of taking a generic type, I would probably write a method that takes an instance of an interface like IConvertableToByteArray or something.
public IConvertableToByteArray
{
public byte[] ToByteArray();
}
Then If you needed to allow a specific type to be compatible with that method, you could make an encapsulating class
public IntConvertableToByteArray : IConvertableToByteArray
{
public int Value{get; set;}
public byte[] ToByteArray()
{
insert logic here
}
}
You could use Marshal.StructureToPtr to get an unmanaged representation of the structure (which has to be a 'simple' structure). You might need to special case strings though.
You should also think about the alignment constraints on what you are searching for -- advancing through memory 1 byte at a time will be very slow and wasteful if the item must be 4 or 8 byte aligned.

is it possible to have dynamic struct members dependent to another member in c#

in this case a binary file is written with the file format based on a struct
struct fileformat
{
struct mask
{
bool mem1present
bool mem2present
bool mem3present
//5 bits unused
}
//member only written in file if mem1present is true
byte mem1present
//member only written in file if mem2present is true
byte mem1present
//member only written in file if mem3present is true
byte mem1present
}
is this possible to be implemented in c#
Sure - you have to implement the serialization yourself to some extent, but you can do that easily enough.
It's unclear what sort of serialization you're using - if you're using the "raw" binary serialization from .NET, you want to override GetObjectData to only add the relevant data on serialization, and then in the protected constructor taking a SerializationInfo and a StreamingContext, populate your struct from the same data in reverse. See this MSDN article for some details.
I don't know what happens if you're using XML serialization.
If you're writing your own serialization (i.e. you've got a method such as WriteToStream) then you can choose to represent it however you want, of course.
EDIT: It sounds like you've probably got an existing file format you need to read in, but you can define your own types. It's easy to have a class or struct with multiple members and possibly a mask to say what's set, although without knowing more it may not be the best design. While you can use explicit layout to make this efficient in memory, it's probably easiest just to have separate members:
struct Foo
{
// Bit-set to determine which fields are actually used
private readonly byte mask;
private readonly int value1;
private readonly int value2;
private readonly int value3;
public Foo(byte mask, int value1, int value2, int value3)
{
this.mask = mask;
this.value1 = value1;
this.value2 = value2;
this.value3 = value3;
}
}
Then somewhere (either in the data type or not), something like:
Foo ReadFoo(Stream stream)
{
byte mask = stream.ReadByte();
int value1 = 0, value2 = 0, value3 = 0;
if ((mask & 1) == 1)
{
// However you do that, depending on your file format
value1 = ReadInt32FromStream(stream);
}
if ((mask & 2) == 2)
{
// However you do that, depending on your file format
value2 = ReadInt32FromStream(stream);
}
if ((mask & 4) == 4)
{
// However you do that, depending on your file format
value3 = ReadInt32FromStream(stream);
}
return new Foo(mask, value1, value2, value3);
}
By the way, I would seriously consider whether a struct is really the best approach here - consider using a class instead. I very rarely create my own structs.
Note: Your sample shows only the declaration of a nested struct type, not an instance of it.
From your question wording, you need an instance member.
struct fileformat
{
struct mask // type declaration only
{
bool mem1present
bool mem2present
bool mem3present
//5 bits unused
}
public mask mask; // <-- Member instance here
}
I apologize if I've misunderstood. Perhaps your struct was only to communicate the structure of the file to us?

C# equivalent to VB6 'Type'

I am trying to port a rather large source from VB6 to C#. This is no easy task - especially for me being fairly new to C#.net. This source uses numerous Windows APIs as well as numerous Types. I know that there is no equivalent to the VB6 Type in C# but I'm sure there is a way to reach the same outcome. I will post some code below to further explain my request.
VB6:
Private Type ICONDIRENTRY
bWidth As Byte
bHeight As Byte
bColorCount As Byte
bReserved As Byte
wPlanes As Integer
wBitCount As Integer
dwBytesInRes As Long
dwImageOffset As Long
End Type
Dim tICONDIRENTRY() As ICONDIRENTRY
ReDim tICONDIRENTRY(tICONDIR.idCount - 1)
For i = 0 To tICONDIR.idCount - 1
Call ReadFile(lFile, tICONDIRENTRY(i), Len(tICONDIRENTRY(i)), lRet, ByVal 0&)
Next i
I have tried using structs and classes - but no luck so far.
I would like to see a conversion of this Type structure, but if someone had any clue as to how to convert the entire thing it would be unbelievably helpful. I have spent countless hours on this small project already.
If it makes any difference, this is strictly for educational purposes only.
Thank you for any help in advance,
Evan
struct is the equivalent. You'd express it like this:
struct IconDirEntry {
public byte Width;
public byte Height;
public byte ColorCount;
public byte Reserved;
public int Planes;
public int BitCount;
public long BytesInRes;
public long ImageOffset;
}
You declare a variable like this:
IconDirEntry entry;
Generally, in C#, type prefixes are not used, nor are all caps, except possibly for constants. structs are value types in C#, so that means that they are always passed by value. It looks like you're passing them in to a method that's populating them. If you want that usage, you'll have to use classes.
I'm not exactly sure what your issue is but this is a small ex of how to use a struct.
struct aStrt
{
public int A;
public int B;
}
static void Main(string[] args)
{
aStrt saStrt;
saStrt.A = 5;
}
Your question is not clear ..
What issues are you facing when you are using either struct or class and define those field members? Are you not able to access those members using an instance created for that class ??
Else, declare the class as static and make all the members inside the class also as static , so that u can access them without any instance being created!!
Maybe you trying to get something like this?
struct IconDirEntry
{
public byte Width;
// etc...
}
IconDirEntry[] tICONDIRENTRY = new IconDireEntry[tICONDIR.idCount - 1];

qt to c# what does : operator mean within struct

I have a block of code that i'm trying to covert from an old qt file into C# but i'm a little unclear what is going on in the struct within the union below. I'm not sure what the ':' does... i'm guessing it sets the size but could not find any documentation on this. Also since C# does not have unions what is the best practice for converting something like this. Thank you
union uAWord
{
uAWord()
: m_AWord(0) {}
struct sBcdAWord
{
quint32 m_O :8;
quint32 m_S :2;
quint32 m_D :18;
quint32 m_SS :3;
quint32 m_P :1;
}
sBcdAWord m_F;
quint32 m_AWord;
}
This is what is called BitFields. the portion sBcdWord is a 32 bit word, and each field is a portion of that word taking respectively 8,2,18,3,1 BIT:
So the word layout is as below:
Bit0-Bit7 m_0
Bit8-Bit9 m_S
Bit10-Bit27 m_D
Bit28-Bit30 m_ss
Bit31 m_P
How to port this in C# depends if you are convettually porting the code, or if you need to PInvoke. In the case of PInvoke the best solution is probably to map sBcdAWord as an Unit32, and create some accessor strategy to mask on reading writing. If it is a code port, use separeted properties would be good unless there is special needing in memory usage saving.
That syntax is used to declare bitfields. The number is the number of bits for that value. See for example http://publib.boulder.ibm.com/infocenter/macxhelp/v6v81/index.jsp?topic=%2Fcom.ibm.vacpp6m.doc%2Flanguage%2Fref%2Fclrc03defbitf.htm
A good conversion to C# depends on the case I guess. As long as you are not too space-conscious, I'd just keep all needed values in parallel in a class.
That initializes m_aWord to 0.
To answer your other question, in C# you'd likely want a struct, and you'd need to use attributes to get union-like behavior out of it.
This particular example could be somewhat like:
[StructLayout(LayoutKind.Explicit)]
struct uAWord {
[FieldOffset(0)]
private uint theWord = 0;
[FieldOffset(0)]
public int m_P;
[FieldOffset(1)]
public int m_S;
[FieldOffset(3)]
public int m_SS;
[FieldOffset(7)]
public int m_O;
[FieldOffset(18)]
public int m_D;
public uAWord(uint theWord){
this.theWord = theWord;
}
}
The LayoutKind.Explicit indicates you will tell it where in the memory to map each field and the FieldOffset(int) tells which bit to start each field on. See this for more details. You'd assign this struct by setting the uint theWord in the constructor, then each of the other properties would access a chunk starting at a different memory address.
Unfortunately, that actually isn't correct. You'll need to use properties and do some bitmasking/shifting to get it right. Like this:
struct uAWord {
private uint theWord = 0;
public int m_P {get {return (theWord & 0x01);}}
public int m_S {get {return (theWord & 0x02) << 2;}}
public int m_SS {get {return (theWord & 0x04) << 3;}}
public int m_0 {get {return (theWord & 0x18) << 6;}}
}

Convert System.Web.UI.WebControls.Unit to int in c#

How can I convert from an ASP.NET Unit structure to int in c#? Or reverse?
The Unit type has a Value property. This is a double, but you can cast it to an int if you want. The casting may cause a loss of precision, but you are probably aware of that.
To create a Unit just use the constructor that takes an int.
If you mean the Unit class:
The Unit class can represent values
only between -32768 and 32767.
But it depends if you want the Pixel or Percentage value.
myUnit.Value will get the value as pointed out.
Use the constructor public Unit(int value) to convert back.
If you mean a uint: there's 2 possible obvious ways:
int n = Convert.ToInt32(myUint);
int n = (int)myUint;
For ASP.NET Unit:
unit.IsEmpty ? 0 : Convert.ToInt32(unit.Value);
Use Unit.Value property. It will return double and you can cast it to int
Something like (int)xyz.Value
WEhere xyz is the unit variable
To convert int to unit use new Unit(value)
Probably he need this:
int myInt = 1;
uint myUint = (uint)myInt;
uint myUint = 1;
int myInt = (int)myUint;
The Value property returns a dobule, that you can convert to an integer:
int h = (int)someControl.Height.Value;
However, the conversion might not make sense for some unit types. If you don't know for certain that the unit is of a specific type, you would want to check the Type property first.
Convert.Toint32( UInt );
I guess u meant UInt not Unit
EDIT : Ok thought you meant uint sorry

Categories