Search Results

Search found 763 results on 31 pages for 'casting'.

Page 7/31 | < Previous Page | 3 4 5 6 7 8 9 10 11 12 13 14  | Next Page >

  • GCC doesn't like C++ style casts with spaces

    - by uj2
    I am porting some C++ code to GCC, and apperantly it isn't happy with C++ style casting when sapces are involved, as in unsigned int(-1), long long(ShortVar) etc... It gives an error: expected primary-expression before 'long'. Is there any way to make peace with GCC without going over each one of those and rewrite in c-style?

    Read the article

  • Storing a type in C++

    - by perimosocordiae
    Is it possible to store a type name as a C++ variable? For example, like this: type my_type = int; // or string, or Foo, or any other type void* data = ...; my_type* a = (my_type*) data; I know that 99.9% of the time there's a better way to do what you want without resorting to casting void pointers, but I'm curious if C++ allows this sort of thing.

    Read the article

  • Does (size_t)((char *)0) ever not evaluate to 0?

    - by Bruce Christensen
    According to the responses in "Why subtract null pointer in offsetof()?" (and my reading of K&R), the C standard doesn't require that (size_t)((char *)0) == 0. Still, I've never seen a situation where casting a null pointer to an integer type evaluates to anything else. If there is a compiler or scenario where (size_t)((char *)0) != 0, what is it?

    Read the article

  • C# 4.0: casting dynamic to static

    - by Kevin Won
    This is an offshoot question that's related to another I asked here. I'm splitting it off because it's really a sub-question: I'm having difficulties casting an object of type dynamic to another (known) static type. I have an ironPython script that is doing this: import clr clr.AddReference("System") from System import * def GetBclUri(): return Uri("http://google.com") note that it's simply newing up a BCL System.Uri type and returning it. So I know the static type of the returned object. now over in C# land, I'm newing up the script hosting stuff and calling this getter to return the Uri object: dynamic uri = scriptEngine.GetBclUri(); System.Uri u = uri as System.Uri; // casts the dynamic to static fine Works no problem. I now can use the strongly typed Uri object as if it was originally instantiated statically. however.... Now I want to define my own C# class that will be newed up in dynamic-land just like I did with the Uri. My simple C# class: namespace Entity { public class TestPy // stupid simple test class of my own { public string DoSomething(string something) { return something; } } } Now in Python, new up an object of this type and return it: sys.path.append(r'C:..path here...') clr.AddReferenceToFile("entity.dll") import Entity.TestPy def GetTest(): return Entity.TestPy(); // the C# class then in C# call the getter: dynamic test = scriptEngine.GetTest(); Entity.TestPy t = test as Entity.TestPy; // t==null!!! here, the cast does not work. Note that the 'test' object (dynamic) is valid--I can call the DoSomething()--it just won't cast to the known static type string s = test.DoSomething("asdf"); // dynamic object works fine so I'm perplexed. the BCL type System.Uri will cast from a dynamic type to the correct static one, but my own type won't. There's obviously something I'm not getting about this...

    Read the article

  • Casting to a struct from LPVOID - C

    - by Jamie Keeling
    Hello, I am writing a simple console application which will allow me to create a number of threads from a set of parameters passed through the arguments I provide. DWORD WINAPI ThreadFunc(LPVOID threadData) { } I am packing them into a struct and passing them as a parameter into the CreateThread method and trying to unpack them by casting them to the same type as my struct from the LPVOID. I'm not sure how to cast it to the struct after getting it through so I can use it in the method itself, i've tried various combinations (Example attatched) but it won't compile. Struct: #define numThreads 1 struct Data { int threads; int delay; int messages; }; Call to method: HANDLE hThread; DWORD threadId; struct Data *tData; tData->threads = numThreads; tData->messages = 3; tData->delay = 1000; // Create child thread hThread = CreateThread( NULL, // lpThreadAttributes (default) 0, // dwStackSize (default) ThreadFunc, // lpStartAddress &tData, // lpParameter 0, // dwCreationFlags &threadId // lpThreadId (returned by function) ); My attempt: DWORD WINAPI ThreadFunc(LPVOID threadData) { struct Data tData = (struct Data)threadData; int msg; for(msg = 0; msg<5; msg++) { printf("Message %d from child\n", msg); } return 0; } Compiler error: error C2440: 'type cast' : cannot convert from 'LPVOID' to 'Data' As you can see I have implemented a way to loop through a number of messages already, I'm trying to make things slightly more advanced and add some further functionality.

    Read the article

  • Strange casting problem with tm structure

    - by egiakoum1984
    I have the following casting problem when my data structure sSpecificData contains a field of type tm: typedef struct { unsigned char data[10000]; } sDataBuffer; typedef struct { int m_Id; sDataBuffer m_Data; } sData; typedef struct { int m_value1; int m_value2; tm m_Date; } sSpecificData; const int SPECIFIC_SVC_DATA_SIZE = sizeof(sSpecificData); typedef struct { int m_Id; sSpecificData m_Data; } sMyData; int main(void) { sData svc; sMyData* ptr1 = (sMyData*) &svc; sSpecificData* ptr2; ptr2 = (sSpecificData*) &svc.m_Data; ptr1->m_Data.m_value1 = 90; ptr1->m_Data.m_value2 = 80; cout << ptr1->m_Data.m_value1 << endl; cout << ptr1->m_Data.m_value2 << endl; cout << ptr2->m_value1 << endl; cout << ptr2->m_value2 << endl; return 0; } Without the field "tm m_Date;" as part of the sSpecificData, the output is correct: 90 80 90 80 With the field "tm m_Date;" as part of the sSpecificData, the output is wrong: 90 80 0 <-- ! 90 <-- ! Is there any idea why my example doesn't work when there is field of type tm as part of the sSpecificData? Thanks!

    Read the article

  • JTree TreePath casting problem

    - by newbie123
    I got this casting problem java.lang.String cannot be cast to java.io.File, when I trying to do this TreePath p = new TreePath(new Object[] {"src","file","My Diary" }); This is my jtree file model class FileTreeModel implements TreeModel { private FileNode root; public FileTreeModel(String directory) { root = new FileNode(directory); } public Object getRoot() { return root; } public Object getChild(Object parent, int index) { FileNode parentNode = (FileNode) parent; return new FileNode(parentNode, parentNode.listFiles()[index].getName()); } public int getChildCount(Object parent) { FileNode parentNode = (FileNode) parent; if (parent == null || !parentNode.isDirectory() || parentNode.listFiles() == null) { return 0; } return parentNode.listFiles().length; } public boolean isLeaf(Object node) { return (getChildCount(node) == 0); } public int getIndexOfChild(Object parent, Object child) { FileNode parentNode = (FileNode) parent; FileNode childNode = (FileNode) child; return Arrays.asList(parentNode.list()).indexOf(childNode.getName()); } public void valueForPathChanged(TreePath path, Object newValue) { } public void addTreeModelListener(TreeModelListener l) { } public void removeTreeModelListener(TreeModelListener l) { } } class FileNode extends java.io.File { public FileNode(String directory) { super(directory); } public FileNode(FileNode parent, String child) { super(parent, child); } @Override public String toString() { return getName(); } }

    Read the article

  • [nHibernate] casting string to bool using nHibernate Criteria

    - by code-zoop
    I have an nHibernate query using Criteria, and I am trying to cast a string to bool in the query itself. I have done the same with casting a string to int, and that works well (the "DataField" property is "1" as a string): var result = Session .CreateCriteria<Car>() .Add(Restrictions.Eq((Projections.Cast(NHibernateUtil.Int32, Projections.Property("DataField"), 1)) .List<Car>(); tx.Commit(); But I am trying to do the same with bool, but I do not get the expected result: var result = Session .CreateCriteria<Car>() .Add(Restrictions.Eq((Projections.Cast(NHibernateUtil.bool, Projections.Property("DataField"), true)) .List<Car>(); tx.Commit(); "DataField" is the string "True", but the result in an empty list, where it should contain 100 elements with the "DataField" property string set to "True". I have tried with the string "true", and "1", but the result is still an empty List. [EDIT] As Commented below, I could check for the string "True" or "False", but I would say this is a more general question than just for the Boolean. Note that the idea is to have some sort of key value representation of the data, where the value can be different data types. I need the value table to contain all data, so storing the data as string seems like the cleanest solution! I have been able to use the method above to store both int and double as string, and to the cast in the query, but I have not succeeded using the same method for DateDime and Boolean. And for DateTime it is crucial to have the actual DateTime object. How can I make the cast from string to bool, and string to DateTime work in the queries? Thanks

    Read the article

  • Scala implicit dynamic casting

    - by weakwire
    I whould like to create a scala Views helper for Android Using this combination of trait and class class ScalaView(view: View) { def onClick(action: View => Any) = view.setOnClickListener(new OnClickListener { def onClick(view: View) { action(view) } }) } trait ScalaViewTrait { implicit def view2ScalaView(view: View) = new ScalaView(view) } I'm able to write onClick() like so class MainActivity extends Activity with ScalaViewTrait { //.... val textView = new TextView(this) textView.onClick(v => v.asInstanceOf[TextView] setText ("asdas")) } My concern is that i want to avoid casting v to TextView v will always be TextView if is applied to a TextView LinearLayout if applied to LinearLayout and so on. Is there any way that v gets dynamic casted to whatever view is applied? Just started with Scala and i need your help with this. UPDATE With the help of generics the above get's like this class ScalaView[T](view: View) { def onClick(action: T => Any) = view.setOnClickListener(new OnClickListener { def onClick(view: View) { action(view.asInstanceOf[T]) } }) } trait ScalaViewTrait { implicit def view2ScalaView[T](view: View) = new ScalaView[T](view) } i can write onClick like this view2ScalaView[TextView](textView) .onClick(v => v.setText("asdas")) but is obvious that i don't have any help from explicit and i moved the problem instead or removing it

    Read the article

  • C# error casting from double to int32

    - by orfix
    using NUF = NUnit.Framework; [NUF.Test]public void DifferentCastingTest() { NUF.Assert.That((int)0.499999D, NUF.Is.EqualTo(0)); NUF.Assert.That((int)0.500000D, NUF.Is.EqualTo(0)); // !!! row 1 NUF.Assert.That((int)1.499999D, NUF.Is.EqualTo(1)); NUF.Assert.That((int)1.500000D, NUF.Is.EqualTo(1)); // !!! row 2 NUF.Assert.That(System.Convert.ToInt32(0.499999D), NUF.Is.EqualTo(0)); NUF.Assert.That(System.Convert.ToInt32(0.500000D), NUF.Is.EqualTo(0)); // !!! NUF.Assert.That(System.Convert.ToInt32(1.499999D), NUF.Is.EqualTo(1)); NUF.Assert.That(System.Convert.ToInt32(1.500000D), NUF.Is.EqualTo(2)); //!!! row 3 } The same double value (1.5D) is converted in different way by casting and Convert.ToInt32 (see row 2 and 3), and two double with same mantissa (0.5 and 1.5) is rounded in different mode (see row 1 and 2). Is it a bug?

    Read the article

  • gcc, strict-aliasing, and casting through a union

    - by Joseph Quinsey
    About a year ago the following paragraph was added to the GCC Manual, version 4.3.4, regarding -fstrict-aliasing: Similarly, access by taking the address, casting the resulting pointer and dereferencing the result has undefined behavior [emphasis added], even if the cast uses a union type, e.g.: union a_union { int i; double d; }; int f() { double d = 3.0; return ((union a_union *)&d)->i; } Does anyone have an example to illustrate this undefined behavior? Note this question is not about what the C99 standard says, or does not say. It is about the actual functioning of gcc, and other existing compilers, today. My simple, naive, attempt fails. For example: #include <stdio.h> union a_union { int i; double d; }; int f1(void) { union a_union t; t.d = 3333333.0; return t.i; // gcc manual: 'type-punning is allowed, provided ...' } int f2(void) { double d = 3333333.0; return ((union a_union *)&d)->i; // gcc manual: 'undefined behavior' } int main(void) { printf("%d\n", f1()); printf("%d\n", f2()); return 0; } works fine, giving on CYGWIN: -2147483648 -2147483648 Also note that taking addresses is obviously wrong (or right, if you are trying to illustrate undefined behavior). For example, just as we know this is wrong: extern void foo(int *, double *); union a_union t; t.d = 3.0; foo(&t.i, &t.d); // UD behavior so is this wrong: extern void foo(int *, double *); double d = 3.0; foo(&((union a_union *)&d)->i, &d); // UD behavior For background discussion about this, see for example: http://www.open-std.org/jtc1/sc22/wg14/www/docs/n1422.pdf http://gcc.gnu.org/ml/gcc/2010-01/msg00013.html http://davmac.wordpress.com/2010/02/26/c99-revisited/ http://cellperformance.beyond3d.com/articles/2006/06/understanding-strict-aliasing.html http://stackoverflow.com/questions/98650/what-is-the-strict-aliasing-rule http://stackoverflow.com/questions/2771023/c99-strict-aliasing-rules-in-c-gcc/2771041#2771041 The first link, draft minutes of an ISO meeting seven months ago, notes in section 4.16: Is there anybody that thinks the rules are clear enough? No one is really able to interpret tham.

    Read the article

  • Cast from Void* to TYPE* using C++ style cast: static_cast or reinterpret_cast

    - by David Relihan
    So if your converting from Void* to Type* or from Type* to Void* should you use: void func(void *p) { Params *params = static_cast<Params*>(p); } or void func(void *p) { Params *params = reinterpret_cast<Params*>(p); } To me static_cast seems the more correct but I've seen both used for the same purpose. Also, does the direction of the conversion matter. i.e. should I still use static_cast for: _beginthread(func,0,static_cast<void*>(params) I have read the other questions on C++ style casting but I'm still not sure what the correct way is for this scenario (I think it is static_cast)

    Read the article

  • Question about member function pointers in a heirarchy

    - by Jesse Beder
    I'm using a library that defines an interface: template<class desttype> void connect(desttype* pclass, void (desttype::*pmemfun)()); and I have a small heirarchy class base { void foo(); }; class derived: public base { ... }; In a member function of derived, I want to call connect(this, &derived::foo); but it seems that &derived::foo is actually a member function pointer of base; gcc spits out error: no matching function for call to ‘connect(derived* const&, void (base::* const&)())’ I can get around this by explicitly casting this to base *; but why can't the compiler match the call with desttype = base (since derived * can be implicitly cast to base *)? Also, why is &derived::foo not a member function pointer of derived?

    Read the article

  • How can I type cast EventArgs to have a .point property in c#? [closed]

    - by Sean Smyth
    I'm working with a double click function in c#. the function takes an object and EventArgs as it's parameters: private void gvHL7_DoubleClick(object sender, EventArgs e){ . . . } However, I want to use the .Point property, and EventArgs doesn't have that property. I know that DevExpress.XtraGrid.Views.Grid.GridMenuEventArgs does, but it's saying that's an invalid casting. What type should I cast my EventArgs instance to if I wish to access the .Point property? Edit: The double click function I'm working with is provided by devexpress for their grids.

    Read the article

  • Need help for this syntax: "#define LEDs (char *) 0x0003010"

    - by Noge
    I'm doing programming of a softcore processor, Nios II from Altera, below is the code in one of the tutorial, I manage to get the code working by testing it on the hardware (DE2 board), however, I could not understand the code. #define Switches (volatile char *) 0x0003000 #define LEDs (char *) 0x0003010 void main() { while (1) *LEDs = *Switches; } What I know about #define is that, it is either used to define a constant, or a macro, but why in the above code, there are casting like, (char *) 0x0003010, in #define? why the 2 constants, Switches and LEDs act like a variable instead of a constant? Thanks in advance !

    Read the article

  • AS3 Accessing Variables of Parent Class From Child

    - by TheDarkIn1978
    i'm trying to assign a parent's variable from the parent's child //Parent public class Main extends Sprite { public var selectedSquare:Sprite; public function Main() { //inits and adds new Square child class to display list } ... ------- //Child public function dragSquare(evt:MouseEvent):void { Sprite(parent).selectedSquare = this; //evil doesn't work! parent.addChild(this); this.startDrag(); } i'm receiving this error, but i'm casting parent from displayObjectContainer to a Sprite so i have no idea why it's not working. 1119: Access of possibly undefined property selectedSquare through a reference with static type flash.display:Sprite.

    Read the article

  • floating constants in C

    - by Daziplqa
    Hi floks, I have a question concerning floating constants in C. In Java, the default type of floating point constants in double, so the following will causes a compilation error in java: float f = 100.0; // we either need to uses type case operator or put f at the end of the number constant. This is because the default floating-point constants are of type double and casting from double to float without type cast operator is an error, so we need either add a type case operator or put f at the end of the number. So, Why in C this doesn't produce an error, Is it because the default floating-point constants are of type float, or because the compiler do an implicit down-cast conversion (that doesn't requires type case operator in C)????

    Read the article

  • Avoid incompatible pointer warning when dealing with double-indirection

    - by fnawothnig
    Assuming this program: #include <stdio.h> #include <string.h> static void ring_pool_alloc(void **p, size_t n) { static unsigned char pool[256], i = 0; *p = &pool[i]; i += n; } int main(void) { char *str; ring_pool_alloc(&str, 7); strcpy(str, "foobar"); printf("%s\n", str); return 0; } ... is it possible to somehow avoid the GCC warning test.c:12: warning: passing argument 1 of ‘ring_pool_alloc’ from incompatible pointer type test.c:4: note: expected ‘void **’ but argument is of type ‘char **’ ... without casting to (void**) (or simply disabling the compatibility checks)? Because I would very much like to keep compatibility warnings regarding indirection-level...

    Read the article

  • How to convert from integer to unsigned char in C, given integers larger than 256?

    - by Alf_InPogform
    As part of my CS course I've been given some functions to use. One of these functions takes a pointer to unsigned chars to write some data to a file (I have to use this function, so I can't just make my own purpose built function that works differently BTW). I need to write an array of integers whose values can be up to 4095 using this function (that only takes unsigned chars). However am I right in thinking that an unsigned char can only have a max value of 256 because it is 1 byte long? I therefore need to use 4 unsigned chars for every integer? But casting doesn't seem to work with larger values for the integer. Does anyone have any idea how best to convert an array of integers to unsigned chars?

    Read the article

  • java.lang.classcastExcption

    - by Tara Singh
    Hi, I have an array list of objects in my application. private static ArrayList<Player> userList=new ArrayList<Player>(); In my application, I am converting this list to byte array and then sending it to other clients. At client When I am trying to cast it back to the ArrayList, its giving me casting error. I am doing this in client side after receiving this list as byte array: ArrayList<Player> pl = (ArrayList<Player>) toObject(receivedByteArray); where toObject is my function to convert the byte array to object; Any Suggestions please !!! Thanks.

    Read the article

  • Calling a method on a Object says "disallows late binding"

    - by Maury Markowitz
    I have a calls called DtaDate that stores an integer "key", a string name, a string for the date, and a Date object that is created from that string. I have some code that needs to accept a date-like object. I'd like the user to be able to pass in anything date like - a Date object which I'll extract the information from, another DtaDate, a string with the date in it, or even the key, which I'll use to look up the DtaDate from a collection. So I have this: Friend Sub New(NameIn As String, DateFormulaIn As String, Optional FromDateIn As Object = Nothing) [stuff that works] [check that we got a FromDateIn...] If TypeOf FromDateIn Is DtaDate Then fdk = FromDateIn.Key Ans.FromDate = fdk VB tells me that "Option Strict On disallows late binding". The other cases, where a string or integer is the TypeOf, I use CInt or CStr. But this is the first time I've actually run into a case where the casting is a non-base type. What's the trick?

    Read the article

  • Problem with Mapping Linq-to-Sql on different Types

    - by csharpnoob
    Hi, maybe someone can help. I want to have on mapped Linq-Class different Datatype. This is working: private System.Nullable<short> _deleted = 1; [Column(Storage = "_deleted", Name = "deleted", DbType = "SmallInt", CanBeNull = true)] public System.Nullable<short> deleted { get { return this._deleted; } set { this._deleted = value; } } Sure thing. But no when i want to place some logic for boolean, like this: private System.Nullable<short> _deleted = 1; [Column(Storage = "_deleted", Name = "deleted", DbType = "SmallInt", CanBeNull = true)] public bool deleted { get { if (this._deleted == 1) { return true; } return false; } set { if(value == true) { this._deleted = (short)1; }else { this._deleted = (short)0; } } } I get always runtime error: [TypeLoadException: GenericArguments[2], "System.Nullable`1[System.Int16]", on 'System.Data.Linq.Mapping.PropertyAccessor+Accessor`3[T,V,V2]' violates the constraint of type parameter 'V2'.] I can't change the database to bit.. I need to have casting in mapping class.

    Read the article

  • How do I DYNAMICALLY cast in C# and return for a property

    - by ken-forslund
    I've already read threads on the topic, but can't find a solution that fits. I'm working on a drop-down list that takes an enum and uses that to populate itself. i found a VB.NET one. During the porting process, I discovered that it uses DirectCast() to set the type as it returns the SelectedValue. See the original VB here: http://jeffhandley.com/archive/2008/01/27/enum-list-dropdown-control.aspx the gist is, the control has Type _enumType; //gets set when the datasource is set and is the type of the specific enum The SelectedValue property kind of looks like (remember, it doesn't work): public Enum SelectedValue //Shadows Property { get { // Get the value from the request to allow for disabled viewstate string RequestValue = this.Page.Request.Params[this.UniqueID]; return Enum.Parse(_enumType, RequestValue, true) as _enumType; } set { base.SelectedValue = value.ToString(); } } Now this touches on a core point that I think was missed in the other discussions. In darn near every example, folks argued that DirectCast wasn't needed, because in every example, they statically defined the type. That's not the case here. As the programmer of the control, I don't know the type. Therefore, I can't cast it. Additionally, the following examples of lines won't compile because c# casting doesn't accept a variable. Whereas VB's CType and DirectCast can accept Type T as a function parameter: return Enum.Parse(_enumType, RequestValue, true); or return Enum.Parse(_enumType, RequestValue, true) as _enumType; or return (_enumType)Enum.Parse(_enumType, RequestValue, true) ; or return Convert.ChangeType(Enum.Parse(_enumType, RequestValue, true), _enumType); or return CastTo<_enumType>(Enum.Parse(_enumType, RequestValue, true)); So, any ideas on a solution? What's the .NET 3.5 best way to resolve this?

    Read the article

  • C++ casted realloc causing memory leak

    - by wyatt
    I'm using a function I found here to save a webpage to memory with cURL: struct WebpageData { char *pageData; size_t size; }; size_t storePage(void *input, size_t size, size_t nmemb, void *output) { size_t realsize = size * nmemb; struct WebpageData *page = (struct WebpageData *)output; page->pageData = (char *)realloc(page->pageData, page->size + realsize + 1); if(page->pageData) { memcpy(&(page->pageData[page->size]), input, realsize); page->size += realsize; page->pageData[page->size] = 0; } return realsize; } and find the line: page->pageData = (char *)realloc(page->pageData, page->size + realsize + 1); is causing a memory leak of a few hundred bytes per call. The only real change I've made from the original source is casting the line in question to a (char *), which my compiler (gcc, g++ specifically if it's a c/c++ issue, but gcc also wouldn't compile with the uncast statement) insisted upon, but I assume this is the source of the leak. Can anyone elucidate? Thanks

    Read the article

  • LINQ .Cast() extension method fails but (type)object works.

    - by Ben Robinson
    To convert between some LINQ to SQL objects and DTOs we have created explicit cast operators on the DTOs. That way we can do the following: DTOType MyDTO = (LinqToSQLType)MyLinq2SQLObj; This works well. However when you try to cast using the LINQ .Cast() extension method it trows an invalid cast exception saying cannot cast type Linq2SQLType to type DTOType. i.e. the below does not work List<DTO.Name> Names = dbContact.tNames.Cast<DTO.Name>() .ToList(); But the below works fine: DAL.tName MyDalName = new DAL.tName(); DTO.Name MyDTOName = (DTO.Name)MyDalName; and the below also works fine List<DTO.Name> Names = dbContact.tNames.Select(name => (DTO.Name)name) .ToList(); Why does the .Cast() extension method throw an invalid cast exception? I have used the .Cast() extension method in this way many times in the past and when you are casting something like a base type to a derived type it works fine, but falls over when the object has an explicit cast operator.

    Read the article

< Previous Page | 3 4 5 6 7 8 9 10 11 12 13 14  | Next Page >