Search Results

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

Page 12/31 | < Previous Page | 8 9 10 11 12 13 14 15 16 17 18 19  | Next Page >

  • How to get rid of void-pointers.

    - by Patrick
    I inherited a big application that was originally written in C (but in the mean time a lot of C++ was also added to it). Because of historical reasons, the application contains a lot of void-pointers. Before you start to choke, let me explain why this was done. The application contains many different data structures, but they are stored in 'generic' containers. Nowadays I would use templated STL containers for it, or I would give all data structures a common base class, so that the container can store pointers to the base class, but in the [good?] old C days, the only solution was to cast the struct-pointer to a void-pointer. Additionally, there is a lot of code that works on these void-pointers, and uses very strange C constructions to emulate polymorphism in C. I am now reworking the application, and trying to get rid of the void-pointers. Adding a common base-class to all the data structures isn't that hard (few days of work), but the problem is that the code is full of constructions like shown below. This is an example of how data is stored: void storeData (int datatype, void *data); // function prototype ... Customer *myCustomer = ...; storeData (TYPE_CUSTOMER, myCustomer); This is an example of how data is fetched again: Customer *myCustomer = (Customer *) fetchData (int datatype, char *key); I actually want to replace all the void-pointers with some smart-pointer (reference-counted), but I can't find a trick to automate (or at least) help me to get rid of all the casts to and from void-pointers. Any tips on how to find, replace, or interact in any possible way with these conversions?

    Read the article

  • Why does null need to be casted?

    - by BlueRaja The Green Unicorn
    The following code does not compile: //int a = ... int? b = (int?) (a != 0 ? a : null); In order to compile, it needs to be changed to int? b = (a != 0 ? a : (int?) null); Since both b = null and b = a are legal, this doesn't make sense to me. Why does null need to be casted, and why can't we simply cast the whole expression (which I know is legal in other cases)?

    Read the article

  • ASP.Net Error - Unable to cast object of type 'System.String' to type 'System.Data.DataTable'.

    - by xtrabits
    I get the below error Unable to cast object of type 'System.String' to type 'System.Data.DataTable'. This is the code I'm using Dim str As String = String.Empty If (Session("Brief") IsNot Nothing) Then Dim dt As DataTable = Session("Brief") If (dt.Rows.Count > 0) Then For Each dr As DataRow In dt.Rows If (str.Length > 0) Then str += "," str += dr("talentID").ToString() Next End If End If Return str Thanks

    Read the article

  • Call the cast operator of template base class within the derived class

    - by yoni
    I have a template class, called Cell, here the definition: template <class T> class OneCell { ..... } I have a cast operator from Cell to T, here virtual operator const T() const { ..... } Now i have derived class, called DCell, here template <class T> class DCell : public Cell<T> { ..... } I need to override the Cell's cast operator (insert a little if), but after I need to call the Cell's cast operator. In other methods it's should be something like virtual operator const T() const { if (...) { return Cell<T>::operator const T; } else throw ... } but i got a compiler error error: argument of type 'const int (Cell::)()const' does not match 'const int' What can I do? Thank you, and sorry about my poor English.

    Read the article

  • How are integers converted to strings under the hood?

    - by CrazyJugglerDrummer
    I suppose the real question is how to convert base2/binary to base10. The most common application of this would probably be in creating strings for output: turning a chunk of binary numerical data into an array of characters. How exactly is this done? my guess: Seeing as there probably isn't a string predefined for each numerical value, I'm guessing that the computer goes through each bit of the integer from right to left, each time incrementing the appropriate values in the char array/base10 notation places. If we take the number 160 in binary (10100000), it would know that a 1 in the 8th place means 128, so it places 1 into the third column, 2 in the second, and 8 in the third. The 1 in the 6th column means 32, and it would add those values to the second and first place, carrying over if needed. After this it's an easy conversion to actual char codes.

    Read the article

  • How do I tell gcc to relax its restrictions on typecasting when calling a C function from C++?

    - by Daryl Spitzer
    I'm trying to use Cmockery to mock C functions called from C++ code. Because the SUT is in C++, my tests need to be in C++. When I use the Cmockery expect_string() macro like this: expect_string(mock_function, url, "Foo"); I get: my_tests.cpp: In function ‘void test_some_stuff(void**)’: my_tests.cpp:72: error: invalid conversion from ‘void*’ to ‘const char*’ my_tests.cpp:72: error: initializing argument 5 of ‘void _expect_string(const char*, const char*, const char*, int, const char*, int)’ I see in cmockery.h that expect_string is defined: #define expect_string(function, parameter, string) \ expect_string_count(function, parameter, string, 1) #define expect_string_count(function, parameter, string, count) \ _expect_string(#function, #parameter, __FILE__, __LINE__, (void*)string, \ count) And here's the prototype for _expect_string (from cmockery.h): void _expect_string( const char* const function, const char* const parameter, const char* const file, const int line, const char* string, const int count); I believe the problem is that I'm compiling C code as C++, so the C++ compiler is objecting to (void*)string in the expect_string_count macro being passed as the const char* string parameter to the _expect_string() function. I've already used extern "C" around the cmockery.h include in my_tests.cpp like this: extern "C" { #include <cmockery.h> } ...in order to get around name-mangling problems. (See "How do I compile and link C++ code with compiled C code?") Is there a command-line option or some other means of telling g++ how to relax its restrictions on typecasting from my test's C++ code to the C function in cmockery.c? This is the command I'm currently using to build my_tests.cpp: g++ -m32 -I ../cmockery-0.1.2 -c my_tests.cpp -o $(obj_dir)/my_tests.o

    Read the article

  • Java - How to avoid loss of precision during divide and cast to int?

    - by David Buckley
    I have a situation where I need to find out how many times an int goes into a decimal, but in certain cases, I'm losing precision. Here is the method: public int test(double decimalAmount, int divisor) { return (int) (decimalAmount/ (1d / divisor)); } The problem with this is if I pass in 1.2 as the decimal amount and 5 as the divisor, I get 5 instead of 6. How can I restrusture this so I know how many times 5 goes into the decimal amount as an int?

    Read the article

  • boost::dynamic_pointer_cast with const pointer not working ?

    - by ereOn
    Hi, Let's say I have two classes, A and B, where B is a child class of A. I also have the following function: void foo(boost::shared_ptr<const A> a) { boost::shared_ptr<const B> b = boost::dynamic_pointer_cast<const B>(a); // Error ! } Compilation with gcc gives me the following errors: C:\Boost\include/boost/smart_ptr/shared_ptr.hpp: In constructor 'boost::shared_ptr< <template-parameter-1-1> >::shared_ptr(const boost::shared_ptr<Y>&, boost::detail::dynamic_cast_tag) [with Y = const A, T = const B]': C:\Boost\include/boost/smart_ptr/shared_ptr.hpp:522: instantiated from 'boost::shared_ptr<X> boost::dynamic_pointer_cast(const boost::shared_ptr<U>&) [with T = const B, U = const A]' src\a.cpp:10: instantiated from here C:\Boost\include/boost/smart_ptr/shared_ptr.hpp:259: error: cannot dynamic_cast 'r->boost::shared_ptr<const A>::px' (of type 'const class A* const') to type 'const class B*' (source type is not polymorphic) What could possibly be wrong ? Thank you.

    Read the article

  • WCF DataContract Upcasting

    - by Jarred Froman
    I'm trying to take a datacontract object that I received on the server, do some manipulation on it and then return an upcasted version of it however it doesn't seem to be working. I can get it to work by using the KnownType or ServiceKnownType attributes, but I don't want to roundtrip all of the data. Below is an example: [DataContract] public class MyBaseObject { [DataMember] public int Id { get; set; } } [DataContract] public class MyDerivedObject : MyBaseObject { [DataMember] public string Name { get; set; } } [ServiceContract(Namespace = "http://My.Web.Service")] public interface IServiceProvider { [OperationContract] List<MyBaseObject> SaveMyObjects(List<MyDerivedObject> myDerivedObjects); } public class ServiceProvider : IServiceProvider { public List<MyBaseObject> SaveMyObjects(List<MyDerivedObject> myDerivedObjects) { ... do some work ... myDerivedObjects[0].Id = 123; myDerivedObjects[1].Id = 456; myDerivedObjects[2].Id = 789; ... do some work ... return myDerivedObjects.Cast<MyBaseObject>().ToList(); } } Anybody have any ideas how to get this to work without having to recreate new objects or using the KnownType attributes?

    Read the article

  • Using a function with reference as a function with pointers?

    - by epatel
    Today I stumbled over a piece of code that looked horrifying to me. The pieces was chattered in different files, I have tried write the gist of it in a simple test case below. The code base is routinely scanned with FlexeLint on a daily basis, but this construct has been laying in the code since 2004. The thing is that a function implemented with a parameter passing using references is called as a function with a parameter passing using pointers...due to a function cast. The construct has worked since 2004 on Irix and now when porting it actually do work on Linux/gcc too. My question now. Is this a construct one can trust? I can understand if compiler constructors implement the reference passing as it was a pointer, but is it reliable? Are there hidden risks? Should I change the fref(..) to use pointers and risk braking anything in the process? What to you think? #include <iostream> using namespace std; // ---------------------------------------- // This will be passed as a reference in fref(..) struct string_struct { char str[256]; }; // ---------------------------------------- // Using pointer here! void fptr(const char *str) { cout << "fptr: " << str << endl; } // ---------------------------------------- // Using reference here! void fref(string_struct &str) { cout << "fref: " << str.str << endl; } // ---------------------------------------- // Cast to f(const char*) and call with pointer void ftest(void (*fin)()) { void (*fcall)(const char*) = (void(*)(const char*))fin; fcall("Hello!"); } // ---------------------------------------- // Let's go for a test int main() { ftest((void (*)())fptr); // test with fptr that's using pointer ftest((void (*)())fref); // test with fref that's using reference return 0; }

    Read the article

  • Class Cast Exception

    - by iaagty
    why do i get this exception? Map myHash = null myHash = (HashMap)Collections.synchronizedMap(new HashMap()); If i try to use this hashmap, i get java.lang.ClassCastException

    Read the article

  • Invalid conversion from int to int** C++

    - by user69514
    Not sure why I'm getting this error. I have the following: int* arr = new int[25]; int* foo(){ int* i; cout << "Enter an integer:"; cin >> *i; return i; } void test(int** myInt){ *myInt = foo(); } This call here is where I get the error: test(arr[0]); //here i get invalid conversion from int to int**

    Read the article

  • how to convert byte array to image in java?

    - by nemade-vipin
    I am developing a Web application in Java. In that application, I have created webservices in Java. In that webservice, I have created one webmethod which returns the image list in base64 format. The return type of the method is Vector. In webservice tester I can see the SOAP response as xsi:type="xs:base64Binary". Then I called this webmethod in my application. I used the following code: SBTSWebService webService = null; List imageArray = null; List imageList = null; webService = new SBTSWebService(); imageArray = webService.getSBTSWebPort().getAddvertisementImage(); Iterator itr = imageArray.iterator(); while(itr.hasNext()) { String img = (String)itr.next(); byte[] bytearray = Base64.decode(img); BufferedImage imag=ImageIO.read(new ByteArrayInputStream(bytearray)); imageList.add(imag); } In this code I am receiving the error: java.lang.ClassCastException: [B cannot be cast to java.lang.String" on line String img = (String)itr.next(); Is there any mistake in my code? Or is there any other way to bring the image in actual format? Can you provide me the code or link through which I can resolve the above issue? Note:- I already droped this question and I got the suggetion to try the following code Object next = iter.next(); System.out.println(next.getClass()) I tried this code and got the output as byte[] from webservice. but I am not able to convert this byte array to actual image. is there any other way to bring the image in actual format? Can you provide me the code or link through which I can resolve the above issue?

    Read the article

  • IEnumerable.Cast not calling cast overload

    - by Martin Neal
    I'm not understanding something about the way .Cast works. I have an explicit (though implicit also fails) cast defined which seems to work when I use it "regularly", but not when I try to use .Cast. Why? Here is some compilable code that demonstrates my problem. public class Class1 { public string prop1 { get; set; } public int prop2 { get; set; } public static explicit operator Class2(Class1 c1) { return new Class2() { prop1 = c1.prop1, prop2 = c1.prop2 }; } } public class Class2 { public string prop1 { get; set; } public int prop2 { get; set; } } void Main() { Class1[] c1 = new Class1[] { new Class1() {prop1 = "asdf",prop2 = 1}}; //works Class2 c2 = (Class2)c1[0]; //doesn't work: Compiles, but throws at run-time //InvalidCastException: Unable to cast object of type 'Class1' to type 'Class2'. Class2 c3 = c1.Cast<Class2>().First(); }

    Read the article

  • Invalid cast exception

    - by user127147
    I have a simple application to store address details and edit them. I have been away from VB for a few years now and need to refreash my knowledge while working to a tight deadline. I have a general Sub responsible for displaying a form where user can add contact details (by pressing button add) and edit them (by pressing button edit). This sub is stored in a class Contact. The way it is supposed to work is that there is a list with all the contacts and when new contact is added a new entry is displayed. If user wants to edit given entry he or she selects it and presses edit button Public Sub Display() Dim C As New Contact C.Cont = InputBox("Enter a title for this contact.") C.Fname = frmAddCont.txtFName.Text C.Surname = frmAddCont.txtSName.Text C.Address = frmAddCont.txtAddress.Text frmStart.lstContact.Items.Add(C.Cont.ToString) End Sub I call it from the form responsible for adding new contacts by Dim C As New Contact C.Display() and it works just fine. However when I try to do something similar using the edit button I get errors - "Unable to cast object of type 'System.String' to type 'AddressBook.Contact'." Dim C As Contact If lstContact.SelectedItem IsNot Nothing Then C = lstContact.SelectedItem() C.Display() End If I think it may be something simple however I wasn't able to fix it and given short time I have I decided to ask for help here. I have updated my class with advice from other members and here is the final version (there are some problems however). When I click on the edit button it displays only the input box for the title of the contact and actually adds another entry in the list with previous data for first name, second name etc. Public Class Contact Public Contact As String Public Fname As String Public Surname As String Public Address As String Private myCont As String Public Property Cont() Get Return myCont End Get Set(ByVal value) myCont = Value End Set End Property Public Overrides Function ToString() As String Return Me.Cont End Function Sub NewContact() FName = frmAddCont.txtFName.ToString frmStart.lstContact.Items.Add(FName) frmAddCont.Hide() End Sub Public Sub Display() Dim C As New Contact C.Cont = InputBox("Enter a title for this contact.") C.Fname = frmAddCont.txtFName.Text C.Surname = frmAddCont.txtSName.Text C.Address = frmAddCont.txtAddress.Text 'frmStart.lstContact.Items.Add(C.Cont.ToString) frmStart.lstContact.Items.Add(C) End Sub End Class

    Read the article

  • C# 'is' type check on struct - odd .NET 4.0 x86 optimization behavior

    - by Jacob Stanley
    Since upgrading to VS2010 I'm getting some very strange behavior with the 'is' keyword. The program below (test.cs) outputs True when compiled in debug mode (for x86) and False when compiled with optimizations on (for x86). Compiling all combinations in x64 or AnyCPU gives the expected result, True. All combinations of compiling under .NET 3.5 give the expected result, True. I'm using the batch file below (runtest.bat) to compile and test the code using various combinations of compiler .NET framework. Has anyone else seen these kind of problems under .NET 4.0? Does everyone else see the same behavior as me on their computer when running runtests.bat? #@$@#$?? Is there a fix for this? test.cs using System; public class Program { public static bool IsGuid(object item) { return item is Guid; } public static void Main() { Console.Write(IsGuid(Guid.NewGuid())); } } runtest.bat @echo off rem Usage: rem runtest -- runs with csc.exe x86 .NET 4.0 rem runtest 64 -- runs with csc.exe x64 .NET 4.0 rem runtest v3.5 -- runs with csc.exe x86 .NET 3.5 rem runtest v3.5 64 -- runs with csc.exe x64 .NET 3.5 set version=v4.0.30319 set platform=Framework for %%a in (%*) do ( if "%%a" == "64" (set platform=Framework64) if "%%a" == "v3.5" (set version=v3.5) ) echo Compiler: %platform%\%version%\csc.exe set csc="C:\Windows\Microsoft.NET\%platform%\%version%\csc.exe" set make=%csc% /nologo /nowarn:1607 test.cs rem CS1607: Referenced assembly targets a different processor rem This happens if you compile for x64 using csc32, or x86 using csc64 %make% /platform:x86 test.exe echo =^> x86 %make% /platform:x86 /optimize test.exe echo =^> x86 (Optimized) %make% /platform:x86 /debug test.exe echo =^> x86 (Debug) %make% /platform:x86 /debug /optimize test.exe echo =^> x86 (Debug + Optimized) %make% /platform:x64 test.exe echo =^> x64 %make% /platform:x64 /optimize test.exe echo =^> x64 (Optimized) %make% /platform:x64 /debug test.exe echo =^> x64 (Debug) %make% /platform:x64 /debug /optimize test.exe echo =^> x64 (Debug + Optimized) %make% /platform:AnyCPU test.exe echo =^> AnyCPU %make% /platform:AnyCPU /optimize test.exe echo =^> AnyCPU (Optimized) %make% /platform:AnyCPU /debug test.exe echo =^> AnyCPU (Debug) %make% /platform:AnyCPU /debug /optimize test.exe echo =^> AnyCPU (Debug + Optimized) Test Results When running the runtest.bat I get the following results on my Win7 x64 install. > runtest 32 v4.0 Compiler: Framework\v4.0.30319\csc.exe False => x86 False => x86 (Optimized) True => x86 (Debug) False => x86 (Debug + Optimized) True => x64 True => x64 (Optimized) True => x64 (Debug) True => x64 (Debug + Optimized) True => AnyCPU True => AnyCPU (Optimized) True => AnyCPU (Debug) True => AnyCPU (Debug + Optimized) > runtest 64 v4.0 Compiler: Framework64\v4.0.30319\csc.exe False => x86 False => x86 (Optimized) True => x86 (Debug) False => x86 (Debug + Optimized) True => x64 True => x64 (Optimized) True => x64 (Debug) True => x64 (Debug + Optimized) True => AnyCPU True => AnyCPU (Optimized) True => AnyCPU (Debug) True => AnyCPU (Debug + Optimized) > runtest 32 v3.5 Compiler: Framework\v3.5\csc.exe True => x86 True => x86 (Optimized) True => x86 (Debug) True => x86 (Debug + Optimized) True => x64 True => x64 (Optimized) True => x64 (Debug) True => x64 (Debug + Optimized) True => AnyCPU True => AnyCPU (Optimized) True => AnyCPU (Debug) True => AnyCPU (Debug + Optimized) > runtest 64 v3.5 Compiler: Framework64\v3.5\csc.exe True => x86 True => x86 (Optimized) True => x86 (Debug) True => x86 (Debug + Optimized) True => x64 True => x64 (Optimized) True => x64 (Debug) True => x64 (Debug + Optimized) True => AnyCPU True => AnyCPU (Optimized) True => AnyCPU (Debug) True => AnyCPU (Debug + Optimized) tl;dr

    Read the article

  • Can you cast an object to one that implements an interface? (JAVA)

    - by DDP
    Can you cast an object to one that implements an interface? Right now, I'm building a GUI, and I don't want to rewrite the Confirm/Cancel code (A confirmation pop-up) over and over again. So, what I'm trying to do is write a class that gets passed the class it's used in and tells the class whether or not the user pressed Confirm or Cancel. The class always implements a certain interface. Code: class ConfirmFrame extends JFrame implements ActionListener { JButton confirm = new JButton("Confirm"); JButton cancel = new JButton("Cancel"); Object o; public ConfirmFrame(Object o) { // Irrelevant code here add(confirm); add(cancel); this.o = (/*What goes here?*/)o; } public void actionPerformed( ActionEvent evt) { o.actionPerformed(evt); } } I realize that I'm probably over-complicating things, but now that I've run across this, I really want to know if you can cast an object to another object that implements a certain interface.

    Read the article

  • Converting Generic Type into reference type after checking its type using GetType(). How ?

    - by Shantanu Gupta
    i am trying to call a function that is defined in a class RFIDeas_Wrapper(dll being used). But when i checked for type of reader and after that i used it to call function it shows me error Cannot convert type T to RFIDeas_Wrapper. EDIT private List<string> GetTagCollection<T>(T Reader) { TagCollection = new List<string>(); if (Reader.GetType() == typeof(RFIDeas_Wrapper)) { ((RFIDeas_Wrapper)Reader).OpenDevice(); // here Reader is of type RFIDeas_Wrapper //, but i m not able to convert Reader into its datatype. string Tag_Id = ((RFIDeas_Wrapper)Reader).TagID(); //Adds Valid Tag Ids into the collection if(Tag_Id!="0") TagCollection.Add(Tag_Id); } else if (Reader.GetType() == typeof(AlienReader)) TagCollection = ((AlienReader)Reader).TagCollection; return TagCollection; } ((RFIDeas_Wrapper)Reader).OpenDevice(); , ((AlienReader)Reader).TagCollection; I want this line to be executed without any issue. As Reader will always be of the type i m specifying. How to make compiler understand the same thing.

    Read the article

  • Is private members hacking a defined behaviour ?

    - by ereOn
    Hi, Lets say I have the following class: class BritneySpears { public: int getValue() { return m_value; }; private: int m_value; }; Which is an external library (that I can't change). I obviously can't change the value of m_value, only read it. Even subclassing BritneySpears won't work. What if I define the following class: class AshtonKutcher { public: int getValue() { return m_value; }; public: int m_value; }; And then do: BritneySpears b; // Here comes the ugly hack AshtonKutcher* a = reinterpret_cast<AshtonKutcher*>(&b); a->m_value = 17; // Print out the value std::cout << b.getValue() << std::endl; I know this is a bad practice. But just for curiosity: is this guaranted to work ? Is it a defined behaviour ? Bonus question: Have you ever had to use such an ugly hack ? Thanks !

    Read the article

< Previous Page | 8 9 10 11 12 13 14 15 16 17 18 19  | Next Page >