Search Results

Search found 1466 results on 59 pages for 'sizeof'.

Page 3/59 | < Previous Page | 1 2 3 4 5 6 7 8 9 10 11 12  | Next Page >

  • mySQL: Order by field size/length

    - by Sadi
    Here is a table structure (e.g. test): __________________________________________ | Field Name | Data Type | |________________|_________________________| | id | BIGINT (20) | |________________|_________________________| | title | varchar(25) | |________________|_________________________| | description | text | |________________|_________________________| A query like: SELECT * FROM TEST ORDER BY description; But I would like to order by the field size/length of the field description. The field type will be TEXT or BLOB.

    Read the article

  • I was stuck in implementing Simple Ftp with Winsock [migrated]

    - by user67449
    I want to implement a SimpleFtp with Winsock. But I was stuck in the maybe the file stream reading and writing. This is the Server. #include <WinSock2.h> #include <memory.h> #include <stdio.h> #include <iostream> using namespace std; #pragma comment(lib, "ws2_32.lib") #define MAX_FILE_NAME 100 #define DATA_PACK_SIZE 80*1000 // ??DataPack?????80KB #define SOCKKET_BUFFER_SIZE 80*1000 // socket??? #define FILE_BUFFER_SIZE DATA_PACK_SIZE-MAX_FILE_NAME-4*sizeof(int)-sizeof(u_long) //?????,??,??????content????? #define CONTENT_SIZE FILE_BUFFER_SIZE // DataPack?????content??? // Define a structure to hold the content of a file typedef struct FilePack{ char fName[MAX_FILE_NAME]; // File's name int fLen; // File's length int packNum; // Number of the DataPack int packLen; // DataPack's length int packCount; int contenLen; // the content length the DataPack actually holds u_long index; // ?????????? char content[CONTENT_SIZE]; // DataPack?????? }DataPack, *pDataPack; void WinsockInitial(){ WSADATA wsaData; WORD wVersionRequested; int err; wVersionRequested=MAKEWORD(2,2); err=WSAStartup(wVersionRequested, &wsaData); if(err!=0){ cout<<"Error at WSAStartup()."<<endl; exit(0); } if( LOBYTE(wsaData.wVersion)!=2 || HIBYTE(wsaData.wVersion)!=2 ){ cout<<"Error at version of Winsock. "<<endl; WSACleanup(); exit(0); } } void SockBind(SOCKET sock, int port, sockaddr_in &addrsock){ addrsock.sin_family=AF_INET; addrsock.sin_port=htons(port); addrsock.sin_addr.S_un.S_addr=htonl(INADDR_ANY); if( bind(sock, (sockaddr*)&addrsock, sizeof(addrsock)) == SOCKET_ERROR ){ cout<<"Error at bind(). Error: "<<GetLastError()<<endl; closesocket(sock); WSACleanup(); exit(0); } } void SockListen(SOCKET sock, int bak){ int err=listen(sock, bak); if(err==SOCKET_ERROR){ cout<<"Error at listen()."<<WSAGetLastError()<<endl; closesocket(sock); WSACleanup(); exit(0); } } int SockSend(DataPack &dataPack, SOCKET sock, char *sockBuf){ int bytesLeft=0, bytesSend=0; int idx=0; bytesLeft=sizeof(dataPack); // ?DataPack?????sockBuf??? memcpy(sockBuf, &dataPack, sizeof(dataPack)); while(bytesLeft>0){ bytesSend=send(sock, &sockBuf[idx], bytesLeft, 0); if(bytesSend==SOCKET_ERROR){ cout<<"Error at send()."<<endl; return 1; } bytesLeft-=bytesSend; idx+=bytesSend; } return 0; } int GetFileLen(FILE *fp){ // ?????? if(fp==NULL){ cout<<"Invalid argument. Error at GetFileLen()."<<endl; exit(0); } fseek(fp, 0, SEEK_END); int tempFileLen=ftell(fp); fseek(fp, 0, SEEK_SET); return tempFileLen; } int main(){ int err; sockaddr_in addrServ; int port=8000; // Initialize Winsock WinsockInitial(); // Create a socket SOCKET sockListen=socket(AF_INET, SOCK_STREAM, IPPROTO_TCP); if(sockListen==INVALID_SOCKET){ cout<<"Error at socket()."<<endl; WSACleanup(); return 1; } // Bind the socket. SockBind(sockListen, port, addrServ); // Listen for incoming connection requests cout<<"Waiting for incoming connection requests..."<<endl; SockListen(sockListen, 5); // Accept the connection request. sockaddr_in addrClient; int len=sizeof(addrClient); SOCKET sockConn=accept(sockListen, (sockaddr*)&addrClient, &len); if(sockConn!=INVALID_SOCKET){ cout<<"Connected to client successfully."<<endl; } // Set the buffer size of socket char sockBuf[SOCKKET_BUFFER_SIZE]; int nBuf=SOCKKET_BUFFER_SIZE; int nBufLen=sizeof(nBuf); err=setsockopt(sockConn, SOL_SOCKET, SO_SNDBUF, (char*)&nBuf, nBufLen); if(err!=0){ cout<<"Error at setsockopt(). Failed to set buffer size for socket."<<endl; exit(0); } //??????????? err = getsockopt(sockConn, SOL_SOCKET, SO_SNDBUF, (char*)&nBuf, &nBufLen); if( SOCKKET_BUFFER_SIZE != nBuf){ cout<<"Error at setsockopt(). ?socket????????"<<endl; closesocket(sockListen); closesocket(sockConn); WSACleanup(); exit(0); } //------------------------------------------------------------------------// DataPack dataPackSend; memset(&dataPackSend, 0, sizeof(dataPackSend)); int bytesRead; int bytesLeft; int bytesSend; int packCount; // Counts how many DataPack needed FILE *frp; // Used to read if(strcpy_s(dataPackSend.fName, "music.mp3")!=0){ cout<<"Error at strcpy_s()."<<endl; return 1; } // Open the file in read+binary mode err=fopen_s(&frp, dataPackSend.fName, "rb"); if(err!=0){ cout<<"Error at fopen_s()."<<endl; return 1; } char fileBuf[FILE_BUFFER_SIZE]; // Set the buffer size of File if(setvbuf(frp, fileBuf, _IONBF, FILE_BUFFER_SIZE)!=0){ cout<<"Error at setvbuf().Failed to set buffer size for file."<<endl; closesocket(sockListen); closesocket(sockConn); WSACleanup(); exit(0); } // Get file's length int fileLen=GetFileLen(frp); cout<<"File ???:"<<fileLen<<" bytes."<<endl; // Calculate how many DataPacks needed packCount=ceil( (double)fileLen/CONTENT_SIZE ); cout<<"File Length: "<<fileLen<<" "<<"Content Size: "<<CONTENT_SIZE<<endl; cout<<"???"<<packCount<<" ?DataPack"<<endl; int i=0; for(i=0; i<packCount; i++){ //?????dataPackSend????? memset(&dataPackSend, 0, sizeof(dataPackSend)); // Fill the dataPackSend if(strcpy_s(dataPackSend.fName, "abc.txt")!=0){ cout<<"Error at strcpy_s()."<<endl; return 1; } dataPackSend.packLen=DATA_PACK_SIZE; dataPackSend.fLen=fileLen; dataPackSend.packCount=packCount; if( packCount==1 ){ //??DataPack??? bytesRead=fread(fileBuf, 1, dataPackSend.fLen, frp); dataPackSend.contenLen=dataPackSend.fLen; memcpy(dataPackSend.content, fileBuf, bytesRead); dataPackSend.packNum=0; //???????DataPack // ?????dataPackSend?Client? if( SockSend(dataPackSend, sockConn, sockBuf)==0 ){ cout<<"??? "<<dataPackSend.packNum<<" ?DataPack"<<endl; } }else if( packCount>1 && i<(packCount-1) ){ // ???(???????) bytesRead=fread(fileBuf, 1, CONTENT_SIZE, frp); dataPackSend.contenLen=CONTENT_SIZE; memcpy(dataPackSend.content, fileBuf, bytesRead); dataPackSend.packNum=i; //?dataPackSend??????Client? if( SockSend(dataPackSend, sockConn, sockBuf)==0 ){ cout<<"??? "<<dataPackSend.packNum<<" ?DataPack."<<endl; } }else{ // ????? bytesRead=fread(fileBuf, 1, (dataPackSend.fLen-i*CONTENT_SIZE), frp); dataPackSend.contenLen=dataPackSend.fLen-i*CONTENT_SIZE; memcpy(dataPackSend.content, fileBuf, bytesRead); dataPackSend.packNum=i; //?dataPackSend???Client? if( SockSend(dataPackSend, sockConn, sockBuf)==0 ){ cout<<"??? "<<dataPackSend.packNum<<" ?DataPack."<<endl; } } } fclose(frp); closesocket(sockListen); closesocket(sockConn); WSACleanup(); return 0; } And this is Client. #include <WinSock2.h> #include <memory.h> #include <stdio.h> #include <iostream> using namespace std; #pragma comment(lib, "ws2_32.lib") #define MAX_FILE_NAME 100 #define DATA_PACK_SIZE 80*1000 // ??DataPack?????80KB #define SOCKKET_BUFFER_SIZE 80*1000 // socket??? #define FILE_BUFFER_SIZE DATA_PACK_SIZE-MAX_FILE_NAME-4*sizeof(int)-sizeof(u_long) //?????,??,??????content????? #define CONTENT_SIZE FILE_BUFFER_SIZE // DataPack?????content??? // Define a structure to hold the content of a file typedef struct FilePack{ char fName[MAX_FILE_NAME]; // File's name int fLen; // File's length int packNum; // Number of the DataPack int packLen; // DataPack's length int packCount; //DataPack??? int contenLen; // the content length the DataPack actually holds u_long index; // ?????????? char content[CONTENT_SIZE]; // DataPack?????? }DataPack, *pDataPack; void WinsockInitial(){ WSADATA wsaData; WORD wVersionRequested; int err; wVersionRequested=MAKEWORD(2,2); err=WSAStartup(wVersionRequested, &wsaData); if(err!=0){ cout<<"Error at WSAStartup()."<<endl; exit(0); } if( LOBYTE(wsaData.wVersion)!=2 || HIBYTE(wsaData.wVersion)!=2 ){ cout<<"Error at version of Winsock. "<<endl; WSACleanup(); exit(0); } } int SockRecv(SOCKET sock, char *sockBuf){ int bytesLeft, bytesRecv; int idx=0; bytesLeft=DATA_PACK_SIZE; while(bytesLeft>0){ bytesRecv=recv(sock, &sockBuf[idx], bytesLeft, 0); if(bytesRecv==SOCKET_ERROR){ cout<<"Error at recv()."<<endl; return 1; } bytesLeft-=bytesRecv; idx+=bytesRecv; } return 0; } int main(){ int err; sockaddr_in addrServ; int port=8000; // Initialize Winsock WinsockInitial(); // Create a socket SOCKET sockClient=socket(AF_INET, SOCK_STREAM, IPPROTO_TCP); if(sockClient==INVALID_SOCKET){ cout<<"Error at socket()."<<endl; WSACleanup(); return 1; } // Set the buffer size of socket char sockBuf[SOCKKET_BUFFER_SIZE]; int nBuf=SOCKKET_BUFFER_SIZE; int nBufLen=sizeof(nBuf); err=setsockopt(sockClient, SOL_SOCKET, SO_RCVBUF, (char*)&nBuf, nBufLen); if(err!=0){ cout<<"Error at setsockopt(). Failed to set buffer size for socket."<<endl; exit(0); } //??????????? err = getsockopt(sockClient, SOL_SOCKET, SO_RCVBUF, (char*)&nBuf, &nBufLen); if( SOCKKET_BUFFER_SIZE != nBuf){ cout<<"Error at getsockopt(). ?socket????????"<<endl; closesocket(sockClient); WSACleanup(); exit(0); } // Connect to the Server addrServ.sin_family=AF_INET; addrServ.sin_port=htons(port); addrServ.sin_addr.S_un.S_addr=inet_addr("127.0.0.1"); err=connect(sockClient, (sockaddr*)&addrServ, sizeof(sockaddr)); if(err==SOCKET_ERROR){ cout<<"Error at connect()."<<GetLastError()<<endl; closesocket(sockClient); WSACleanup(); return 1; }else{ cout<<"Connected to the FTP Server successfully."<<endl; } /* int i=0; int bytesRecv, bytesLeft, bytesWrite; int packCount=0, fLen=0; DataPack dataPackRecv; //?????? SockRecv(sockClient, sockBuf); memcpy(&dataPackRecv, sockBuf, sizeof(dataPackRecv)); cout<<"???? "<<dataPackRecv.packNum<<" ?DataPack."<<endl; cout<<"?DataPack??fName????: "<<dataPackRecv.fName<<endl; //??????? packCount=dataPackRecv.packCount; cout<<"?? "<<packCount<<" ?DataPack."<<endl; fLen=dataPackRecv.fLen; // Create a local file to write into FILE *fwp; err=fopen_s(&fwp, dataPackRecv.fName, "wb"); if(err!=0){ cout<<"Error at creat fopen_s(). Failed to create a local file to write into."<<endl; return 1; } // Set the buffer size of File char fileBuf[FILE_BUFFER_SIZE]; if(setvbuf(fwp, fileBuf, _IONBF, FILE_BUFFER_SIZE)!=0){ cout<<"Error at setvbuf().Failed to set buffer size for file."<<endl; memset(fileBuf, 0, sizeof(fileBuf)); closesocket(sockClient); WSACleanup(); exit(0); } //???????content???? memcpy(fileBuf, dataPackRecv.content, sizeof(dataPackRecv.content)); bytesWrite=fwrite(fileBuf, 1, sizeof(fileBuf), fwp); if(bytesWrite<sizeof(fileBuf)){ cout<<"Error at fwrite(). Failed to write the content of dataPackRecv to local file."<<endl; } //?????packCount-1????????????????? for(int i=1; i<packCount; i++){ // ????????? memset(sockBuf, 0, sizeof(sockBuf)); memset(&dataPackRecv, 0, sizeof(dataPackRecv)); memset(fileBuf, 0, sizeof(fileBuf)); SockRecv(sockClient, sockBuf); memcpy(&dataPackRecv, sockBuf, sizeof(dataPackRecv)); cout<<"???? "<<dataPackRecv.packNum<<" ?DataPack."<<endl; //???? memcpy(fileBuf, dataPackRecv.content, dataPackRecv.contenLen); bytesWrite=fwrite(fileBuf, 1, dataPackRecv.contenLen, fwp); if(bytesWrite<dataPackRecv.contenLen){ cout<<"Error at fwrite(). Failed to write the content of dataPackRecv to local file."<<endl; } } if( (i+1)==packCount ){ cout<<"??DataPack????????!"<<endl; } fclose(fwp); closesocket(sockClient); WSACleanup(); return 0;*/ }

    Read the article

  • VERY simple C program won't compile with VC 64

    - by Paperflyer
    Here is a very simple C program: #include <stdio.h> int main (int argc, char *argv[]) { printf("sizeof(short) = %d\n",(int)sizeof(short)); printf("sizeof(int) = %d\n",(int)sizeof(int)); printf("sizeof(long) = %d\n",(int)sizeof(long)); printf("sizeof(long long) = %d\n",(int)sizeof(long long)); printf("sizeof(float) = %d\n",(int)sizeof(float)); printf("sizeof(double) = %d\n",(int)sizeof(double)); return 0; } While it compiles fine on Win32 (command line: cl main.c), it does not using the Win64 compiler ("c:\Program Files(x86)\Microsoft Visual Studio 9.0\VC\bin\amd64\cl.exe" main.c). Specifically, it sais "error LNK2019: unresolved external symbol printf referenced in function main". As far as I understand this, it can not link to printf, right? Obviously, I have Microsoft Visual C++ Compiler 2008 (Standard enu) x86 and x64 installed and am using the 64-bit flavor of Windows (7). What is the problem here?

    Read the article

  • Question about Virtual Inheritance hierarchy

    - by Summer_More_More_Tea
    Hi there: I encounter this problem when tackling with virtual inheritance. I remember that in a non-virtual inheritance hierarchy, object of sub-class hold an object of its direct super-class. What about virtual inheritance? In this situation, does object of sub-class hold an object of its super-class directly or just hold a pointer pointing to an object of its super-class? By the way, why the output of the following code is: sizeof(A): 8 sizeof(B): 20 sizeof(C): 20 sizeof(C): 36 Code: #include <iostream> using namespace std; class A{ char k[ 3 ]; public: virtual void a(){}; }; class B : public virtual A{ char j[ 3 ]; public: virtual void b(){}; }; class C : public virtual B{ char i[ 3 ]; public: virtual void c(){}; }; class D : public B, public C{ char h[ 3 ]; public: virtual void d(){}; }; int main( int argc, char *argv[] ){ cout << "sizeof(A): " << sizeof( A ) << endl; cout << "sizeof(B): " << sizeof( B ) << endl; cout << "sizeof(C): " << sizeof( C ) << endl; cout << "sizeof(D): " << sizeof( D ) << endl; return 0; } Thanks in advance. Kind regards.

    Read the article

  • Why is there a sizeof... operator in C++0x?

    - by Motti
    I saw that @GMan implemented a version of sizeof... for variadic templates which (as far as I can tell) is equivalent to the built in sizeof.... Doesn't this go against the design principle of not adding anything to the core language if it can be implemented as a library function[citation needed]?

    Read the article

  • Can't seem to get C TCP Server-Client Communications Right

    - by Zeesponge
    Ok i need some serious help here. I have to make a TCP Server Client. When the Client connects to server using a three stage handshake. AFterwards... while the Client is running in the terminal, the user enters linux shell commands like xinput list, ls -1, ect... something that uses standard output. The server accepts the commands and uses system() (in a fork() in an infinite loop) to run the commands and the standard output is redirected to the client, where the client prints out each line. Afterward the server sends a completion signal of "\377\n". In which the client goes back to the command prompt asking for a new command and closes its connection and exit()'s when inputting "quit". I know that you have to dup2() both the STDOUT_FILENO and STDERR_FILENO to the clients file descriptor {dup2(client_FD, STDOUT_FILENO). Everything works accept when it comes for the client to retrieve system()'s stdout and printing it out... all i get is a blank line with a blinking cursor (client waiting on stdin). I tried all kinds of different routes with no avail... If anyone can help out i would greatly appreciate it TCP SERVER CODE include #include <sys/socket.h> #include <stdio.h> #include <string.h> #include <netinet/in.h> #include <signal.h> #include <unistd.h> #include <stdlib.h> #include <errno.h> //Prototype void handle_client(int connect_fd); int main() { int server_sockfd, client_sockfd; socklen_t server_len, client_len; struct sockaddr_in server_address; struct sockaddr_in client_address; server_sockfd = socket(AF_INET, SOCK_STREAM, 0); server_address.sin_family = AF_INET; server_address.sin_addr.s_addr = htonl(INADDR_ANY); server_address.sin_port = htons(9734); server_len = sizeof(server_address); bind(server_sockfd, (struct sockaddr *)&server_address, server_len); /* Create a connection queue, ignore child exit details and wait for clients. */ listen(server_sockfd, 10); signal(SIGCHLD, SIG_IGN); while(1) { printf("server waiting\n"); client_len = sizeof(client_address); client_sockfd = accept(server_sockfd, (struct sockaddr *)&client_address, &client_len); if(fork() == 0) handle_client(client_sockfd); else close(client_sockfd); } } void handle_client(int connect_fd) { const char* remsh = "<remsh>\n"; const char* ready = "<ready>\n"; const char* ok = "<ok>\n"; const char* command = "<command>\n"; const char* complete = "<\377\n"; const char* shared_secret = "<shapoopi>\n"; static char server_msg[201]; static char client_msg[201]; static char commands[201]; int sys_return; //memset client_msg, server_msg, commands memset(&client_msg, 0, sizeof(client_msg)); memset(&server_msg, 0, sizeof(client_msg)); memset(&commands, 0, sizeof(commands)); //read remsh from client read(connect_fd, &client_msg, 200); //check remsh validity from client if(strcmp(client_msg, remsh) != 0) { errno++; perror("Error Establishing Handshake"); close(connect_fd); exit(1); } //memset client_msg memset(&client_msg, 0, sizeof(client_msg)); //write remsh to client write(connect_fd, remsh, strlen(remsh)); //read shared_secret from client read(connect_fd, &client_msg, 200); //check shared_secret validity from client if(strcmp(client_msg, shared_secret) != 0) { errno++; perror("Invalid Security Passphrase"); write(connect_fd, "no", 2); close(connect_fd); exit(1); } //memset client_msg memset(&client_msg, 0, sizeof(client_msg)); //write ok to client write(connect_fd, ok, strlen(ok)); // dup2 STDOUT_FILENO <= client fd, STDERR_FILENO <= client fd dup2(connect_fd, STDOUT_FILENO); dup2(connect_fd, STDERR_FILENO); //begin while... while read (client_msg) from server and >0 while(read(connect_fd, &client_msg, 200) > 0) { //check command validity from client if(strcmp(client_msg, command) != 0) { errno++; perror("Error, unable to retrieve data"); close(connect_fd); exit(1); } //memset client_msg memset(&client_msg, 0, sizeof(client_msg)); //write ready to client write(connect_fd, ready, strlen(ready)); //read commands from client read(connect_fd, &commands, 200); //run commands using system( ) sys_return = system(commands); //check success of system( ) if(sys_return < 0) { perror("Invalid Commands"); errno++; } //memset commands memset(commands, 0, sizeof(commands)); //write complete to client write(connect_fd, complete, sizeof(complete)); } } TCP CLIENT CODE #include <sys/types.h> #include <sys/socket.h> #include <stdio.h> #include <string.h> #include <netinet/in.h> #include <arpa/inet.h> #include <unistd.h> #include <stdlib.h> #include <errno.h> #include "readline.c" int main(int argc, char *argv[]) { int sockfd; int len; struct sockaddr_in address; int result; const char* remsh = "<remsh>\n"; const char* ready = "<ready>\n"; const char* ok = "<ok>\n"; const char* command = "<command>\n"; const char* complete = "<\377\n"; const char* shared_secret = "<shapoopi>\n"; static char server_msg[201]; static char client_msg[201]; memset(&client_msg, 0, sizeof(client_msg)); memset(&server_msg, 0, sizeof(server_msg)); /* Create a socket for the client. */ sockfd = socket(AF_INET, SOCK_STREAM, 0); /* Name the socket, as agreed with the server. */ memset(&address, 0, sizeof(address)); address.sin_family = AF_INET; address.sin_addr.s_addr = inet_addr(argv[1]); address.sin_port = htons(9734); len = sizeof(address); /* Now connect our socket to the server's socket. */ result = connect(sockfd, (struct sockaddr *)&address, len); if(result == -1) { perror("ACCESS DENIED"); exit(1); } //write remsh to server write(sockfd, remsh, strlen(remsh)); //read remsh from server read(sockfd, &server_msg, 200); //check remsh validity from server if(strcmp(server_msg, remsh) != 0) { errno++; perror("Error Establishing Initial Handshake"); close(sockfd); exit(1); } //memset server_msg memset(&server_msg, 0, sizeof(server_msg)); //write shared secret text to server write(sockfd, shared_secret, strlen(shared_secret)); //read ok from server read(sockfd, &server_msg, 200); //check ok velidity from server if(strcmp(server_msg, ok) != 0 ) { errno++; perror("Incorrect security phrase"); close(sockfd); exit(1); } //? dup2 STDIN_FILENO = server socket fd? //dup2(sockfd, STDIN_FILENO); //begin while(1)/////////////////////////////////////// while(1){ //memset both msg arrays memset(&client_msg, 0, sizeof(client_msg)); memset(&server_msg, 0, sizeof(server_msg)); //print Enter Command, scan input, fflush to stdout printf("<<Enter Command>> "); scanf("%s", client_msg); fflush(stdout); //check quit input, if true close and exit successfully if(strcmp(client_msg, "quit") == 0) { printf("Exiting\n"); close(sockfd); exit(EXIT_SUCCESS); } //write command to server write(sockfd, command, strlen(command)); //read ready from server read(sockfd, &server_msg, 200); //check ready validity from server if(strcmp(server_msg, ready) != 0) { errno++; perror("Failed Server Communications"); close(sockfd); exit(1); } //memset server_msg memset(&server_msg, 0, sizeof(server_msg)); //begin looping and retrieving from stdin, //break loop at EOF or complete while((read(sockfd, server_msg, 200) != 0) && (strcmp(server_msg, complete) != 0)) { //while((fgets(server_msg, 4096, stdin) != EOF) || (strcmp(server_msg, complete) == 0)) { printf("%s", server_msg); memset(&server_msg, 0, sizeof(server_msg)); } } }

    Read the article

  • How does object of sub-class record information about its super-class the in a Virtual Inheritance

    - by Summer_More_More_Tea
    Hi there: I encounter this problem when tackling with virtual inheritance. I remember that in a non-virtual inheritance hierarchy, object of sub-class hold an object of its direct super-class. What about virtual inheritance? In this situation, does object of sub-class hold an object of its super-class directly or just hold a pointer pointing to an object of its super-class? By the way, why the output of the following code is: sizeof(A): 8 sizeof(B): 20 sizeof(C): 32 Code: #include <iostream> using namespace std; class A{ char k[ 3 ]; public: virtual void a(){}; }; class B : public virtual A{ char j[ 3 ]; public: virtual void b(){}; }; class C : public virtual B{ char i[ 3 ]; public: virtual void c(){}; }; int main( int argc, char *argv[] ){ cout << "sizeof(A): " << sizeof( A ) << endl; cout << "sizeof(B): " << sizeof( B ) << endl; cout << "sizeof(C): " << sizeof( C ) << endl; return 0; } Thanks in advance. Kind regards.

    Read the article

  • CUDA: cudaMemcpy only works in emulation mode.

    - by Jason
    I am just starting to learn how to use CUDA. I am trying to run some simple example code: float *ah, *bh, *ad, *bd; ah = (float *)malloc(sizeof(float)*4); bh = (float *)malloc(sizeof(float)*4); cudaMalloc((void **) &ad, sizeof(float)*4); cudaMalloc((void **) &bd, sizeof(float)*4); ... initialize ah ... /* copy array on device */ cudaMemcpy(ad,ah,sizeof(float)*N,cudaMemcpyHostToDevice); cudaMemcpy(bd,ad,sizeof(float)*N,cudaMemcpyDeviceToDevice); cudaMemcpy(bh,bd,sizeof(float)*N,cudaMemcpyDeviceToHost); When I run in emulation mode (nvcc -deviceemu) it runs fine (and actually copies the array). But when I run it in regular mode, it runs w/o error, but never copies the data. It's as if the cudaMemcpy lines are just ignored. What am I doing wrong? Thank you very much, Jason

    Read the article

  • How can I detect endianness on a system where all primitive integer sizes are the same?

    - by Joe Wreschnig
    (This question came out of explaining the details of CHAR_BIT, sizeof, and endianness to someone yesterday. It's entirely hypothetical.) Let's say I'm on a platform where CHAR_BIT is 32, so sizeof(char) == sizeof(short) == sizeof(int) == sizeof(long). I believe this is still a standards-conformant environment. The usual way to detect endianness at runtime (because there is no reliable way to do it at compile time) is to make a union { int i, char c[sizeof(int)] } x; x.i = 1 and see whether x.c[0] or x.c[sizeof(int)-1] got set. But that doesn't work on this platform, as I end up with a char[1]. Is there a way to detect whether such a platform is big-endian or little-endian, at runtime? Obviously it doesn't matter inside this hypothetical system, but one can imagine it is writing to a file, or some kind of memory-mapped area, which another machine reads and reconstructs it according to its (saner) memory model.

    Read the article

  • typedef to store pointers in C

    - by seriouslion
    The Size of pointer depends on the arch of the machine. So sizeof(int*)=sizeof(int) or sizeof(int*)=sizeof(long int) I want to have a custom data type which is either int or long int depending on the size of pointer. I tried to use macro #if, but the condition for macros does not allow sizeof operator. Also when using if-else, typedef is limited to the scope of if. if((sizeof(int)==sizeof(int *)){ typedef int ptrtype; } else{ typedef long int ptrtype; } //ptrtype not avialble here Is there any way to define ptrtype globally?

    Read the article

  • Win32 window capture with BitBlt not displaying border

    - by user292533
    I have written some c++ code to capture a window to a .bmp file. BITMAPFILEHEADER get_bitmap_file_header(int width, int height) { BITMAPFILEHEADER hdr; memset(&hdr, 0, sizeof(BITMAPFILEHEADER)); hdr.bfType = ((WORD) ('M' << 8) | 'B'); // is always "BM" hdr.bfSize = 0;//sizeof(BITMAPFILEHEADER) + sizeof(BITMAPINFOHEADER) + (width * height * sizeof(int)); hdr.bfReserved1 = 0; hdr.bfReserved2 = 0; hdr.bfOffBits = (DWORD)(sizeof(BITMAPFILEHEADER) + sizeof(BITMAPINFOHEADER)); return hdr; } BITMAPINFO get_bitmap_info(int width, int height) { BITMAPINFO bmi; memset(&bmi.bmiHeader, 0, sizeof(BITMAPINFOHEADER)); //initialize bitmap header bmi.bmiHeader.biSize = sizeof(BITMAPINFOHEADER); bmi.bmiHeader.biWidth = width; bmi.bmiHeader.biHeight = height; bmi.bmiHeader.biPlanes = 1; bmi.bmiHeader.biBitCount = 4 * 8; bmi.bmiHeader.biCompression = BI_RGB; bmi.bmiHeader.biSizeImage = width * height * 4; return bmi; } void get_bitmap_from_window(HWND hWnd, int * imageBuff) { HDC hDC = GetWindowDC(hWnd); SIZE size = get_window_size(hWnd); HDC hMemDC = CreateCompatibleDC(hDC); RECT r; HBITMAP hBitmap = CreateCompatibleBitmap(hDC, size.cx, size.cy); HBITMAP hOld = (HBITMAP)SelectObject(hMemDC, hBitmap); BitBlt(hMemDC, 0, 0, size.cx, size.cy, hDC, 0, 0, SRCCOPY); //PrintWindow(hWnd, hMemDC, 0); BITMAPINFO bmi = get_bitmap_info(size.cx, size.cy); GetDIBits(hMemDC, hBitmap, 0, size.cy, imageBuff, &bmi, DIB_RGB_COLORS); SelectObject(hMemDC, hOld); DeleteDC(hMemDC); ReleaseDC(NULL, hDC); } void save_image(HWND hWnd, char * name) { int * buff; RECT r; SIZE size; GetWindowRect(hWnd, &r); size.cx = r.right-r.left; size.cy = r.bottom-r.top; buff = (int*)malloc(size.cx * size.cy * sizeof(int)); get_bitmap_from_window(hWnd, buff); BITMAPINFO bmi = get_bitmap_info(size.cx, size.cy); BITMAPFILEHEADER hdr = get_bitmap_file_header(size.cx, size.cy); FILE * fout = fopen(name, "w"); fwrite(&hdr, 1, sizeof(BITMAPFILEHEADER), fout); fwrite(&bmi.bmiHeader, 1, sizeof(BITMAPINFOHEADER), fout); fwrite(buff, 1, size.cx * size.cy * sizeof(int), fout); fflush(fout); fclose(fout); free(buff); } It works find under XP, but under Vista the border of the window is transparent. Using PrintWindow solves the problem, but is unacceptable for performance reasons. Is there a performant code change, or a setting that can be changed to make the border non-transparent?

    Read the article

  • Interleaving Arrays in OpenGL

    - by Benjamin Danger Johnson
    In my pursuit to write code that matches todays OpenGL standards I have found that I am completely clueless about interleaving arrays. I've tried and debugged just about everywhere I can think of but I can't get my model to render using interleaved arrays (It worked when it was configuered to use multiple arrays) Now I know that all the data is properly being parsed from an obj file and information is being copied properly copied into the Vertex object array, but I still can't seem to get anything to render. Below is the code for initializing a model and drawing it (along with the Vertex struct for reference.) Vertex: struct Vertex { glm::vec3 position; glm::vec3 normal; glm::vec2 uv; glm::vec3 tangent; glm::vec3 bitangent; }; Model Constructor: Model::Model(const char* filename) { bool result = loadObj(filename, vertices, indices); glGenVertexArrays(1, &vertexArrayID); glBindVertexArray(vertexArrayID); glGenBuffers(1, &vertexbuffer); glBindBuffer(GL_ARRAY_BUFFER, vertexbuffer); glBufferData(GL_ARRAY_BUFFER, vertices.size() * sizeof(Vertex), &vertices[0], GL_STATIC_DRAW); glGenBuffers(1, &elementbuffer); glBindBuffer(GL_ELEMENT_ARRAY_BUFFER, elementbuffer); glBufferData(GL_ELEMENT_ARRAY_BUFFER, indices.size() * sizeof(unsigned short), &indices[0], GL_STATIC_DRAW); } Draw Model: Model::Draw(ICamera camera) { GLuint matrixID = glGetUniformLocation(programID, "mvp"); GLuint positionID = glGetAttribLocation(programID, "position_modelspace"); GLuint uvID = glGetAttribLocation(programID, "uv"); GLuint normalID = glGetAttribLocation(programID, "normal_modelspace"); GLuint tangentID = glGetAttribLocation(programID, "tangent_modelspace"); GLuint bitangentID = glGetAttribLocation(programID, "bitangent_modelspace"); glm::mat4 projection = camera->GetProjectionMatrix(); glm::mat4 view = camera->GetViewMatrix(); glm::mat4 model = glm::mat4(1.0f); glm::mat4 mvp = projection * view * model; glUniformMatrix4fv(matrixID, 1, GL_FALSE, &mvp[0][0]); glBindVertexArray(vertexArrayID); glEnableVertexAttribArray(positionID); glBindBuffer(GL_ARRAY_BUFFER, vertexbuffer); glVertexAttribPointer(positionID, 3, GL_FLOAT, GL_FALSE, sizeof(Vertex), &vertices[0].position); glEnableVertexAttribArray(uvID); glVertexAttribPointer(uvID, 2, GL_FLOAT, GL_FALSE, sizeof(Vertex), &vertices[0].uv); glEnableVertexAttribArray(normalID); glVertexAttribPointer(normalID, 3, GL_FLOAT, GL_FALSE, sizeof(Vertex), &vertices[0].normal); glEnableVertexAttribArray(tangentID); glVertexAttribPointer(tangentID, 3, GL_FLOAT, GL_FALSE, sizeof(Vertex), &vertices[0].tangent); glEnableVertexAttribArray(bitangentID); glVertexAttribPointer(bitangentID, 3, GL_FLOAT, GL_FALSE, sizeof(Vertex), &vertices[0].bitangent); glBindBuffer(GL_ELEMENT_ARRAY_BUFFER, elementbuffer); glDrawElements(GL_TRIANGLES, indices.size(), GL_UNSIGNED_SHORT, (void*)0); glDisableVertexAttribArray(positionID); glDisableVertexAttribArray(uvID); glDisableVertexAttribArray(normalID); glDisableVertexAttribArray(tangentID); glDisableVertexAttribArray(bitangentID); }

    Read the article

  • LSP packet modify

    - by kellogs
    Hello, anybody care to share some insights on how to use LSP for packet modifying ? I am using the non IFS subtype and I can see how (pseudo?) packets first enter WSPRecv. But how do I modify them ? My inquiry is about one single HTTP response that causes WSPRecv to be called 3 times :((. I need to modify several parts of this response, but since it comes in 3 slices, it is pretty hard to modify it accordingly. And, maybe on other machines or under different conditions (such as high traffic) there would only be one sole WSPRecv call, or maybe 10 calls. What is the best way to work arround this (please no NDIS :D), and how to properly change the buffer (lpBuffers-buf) by increasing it ? int WSPAPI WSPRecv( SOCKET s, LPWSABUF lpBuffers, DWORD dwBufferCount, LPDWORD lpNumberOfBytesRecvd, LPDWORD lpFlags, LPWSAOVERLAPPED lpOverlapped, LPWSAOVERLAPPED_COMPLETION_ROUTINE lpCompletionRoutine, LPWSATHREADID lpThreadId, LPINT lpErrno ) { LPWSAOVERLAPPEDPLUS ProviderOverlapped = NULL; SOCK_INFO *SocketContext = NULL; int ret = SOCKET_ERROR; *lpErrno = NO_ERROR; // // Find our provider socket corresponding to this one // SocketContext = FindAndRefSocketContext(s, lpErrno); if ( NULL == SocketContext ) { dbgprint( "WSPRecv: FindAndRefSocketContext failed!" ); goto cleanup; } // // Check for overlapped I/O // if ( NULL != lpOverlapped ) { /*bla bla .. not interesting in my case*/ } else { ASSERT( SocketContext->Provider->NextProcTable.lpWSPRecv ); SetBlockingProvider(SocketContext->Provider); ret = SocketContext->Provider->NextProcTable.lpWSPRecv( SocketContext->ProviderSocket, lpBuffers, dwBufferCount, lpNumberOfBytesRecvd, lpFlags, lpOverlapped, lpCompletionRoutine, lpThreadId, lpErrno); SetBlockingProvider(NULL); //is this the place to modify packet length and contents ? if (strstr(lpBuffers->buf, "var mapObj = null;")) { int nLen = strlen(lpBuffers->buf) + 200; /*CHAR *szNewBuf = new CHAR[]; CHAR *pIndex; pIndex = strstr(lpBuffers->buf, "var mapObj = null;"); nLen = strlen(strncpy(szNewBuf, lpBuffers->buf, (pIndex - lpBuffers->buf) * sizeof (CHAR))); nLen = strlen(strncpy(szNewBuf + nLen * sizeof(CHAR), "var com = null;\r\n", 17 * sizeof(CHAR))); pIndex += 18 * sizeof(CHAR); nLen = strlen(strncpy(szNewBuf + nLen * sizeof(CHAR), pIndex, 1330 * sizeof (CHAR))); nLen = strlen(strncpy(szNewBuf + nLen * sizeof(CHAR), "if (com == null)\r\n" \ "com = new ActiveXObject(\"InterCommJS.Gateway\");\r\n" \ "com.lat = latitude;\r\n" \ "com.lon = longitude;\r\n}", 111 * sizeof (CHAR))); pIndex = strstr(szNewBuf, "Content-Length:"); pIndex += 16 * sizeof(CHAR); strncpy(pIndex, "1465", 4 * sizeof(CHAR)); lpBuffers->buf = szNewBuf; lpBuffers->len += 128;*/ } if ( SOCKET_ERROR != ret ) { SocketContext->BytesRecv += *lpNumberOfBytesRecvd; } } cleanup: if ( NULL != SocketContext ) DerefSocketContext( SocketContext, lpErrno ); return ret; } Thank you

    Read the article

  • why gcc emits segmentation ,after my code run

    - by gcc
    every time ,why have I encountered with segmentation fault ? still,I have not found my fault sometimes, gcc emits segmentation fault ,sometimes, memory satck limit is exceeded I think you will understand (easily) what is for that code void my_main() { char *tutar[50],tempc; int i=0,temp,g=0,a=0,j=0,d=1,current=0,command=0,command2=0; do{ tutar[i]=malloc(sizeof(int)); scanf("%s",tutar[i]); temp=*tutar[i]; } while(temp=='x'); i=0; num_arrays=atoi(tutar[i]); i=1; tempc=*tutar[i]; if(tempc!='x' && tempc!='d' && tempc!='a' && tempc!='j') { current=1; arrays[current]=malloc(sizeof(int)); l_arrays[current]=calloc(1,sizeof(int)); c_arrays[current]=calloc(1,sizeof(int));} i=1; current=1; while(1) { tempc=*tutar[i]; if(tempc=='x') break; if(tempc=='n') { ++current; arrays[current]=malloc(sizeof(int)); l_arrays[current]=calloc(1,sizeof(int)); c_arrays[current]=calloc(1,sizeof(int)); ++i; continue; } if(tempc=='d') { ++i; command=atoi(tutar[i])-1; free(arrays[command]); free(l_arrays[command]); free(c_arrays[command]); ++i; continue; } if(tempc=='j') { ++i; current=atoi(tutar[i])-1; if(arrays[current]==NULL) { arrays[current]=malloc(sizeof(int)); l_arrays[current]=calloc(1,sizeof(int)); c_arrays[current]=calloc(1,sizeof(int)); ++i; } else { a=l_arrays[current]; j=l_arrays[current]; ++i;} continue; } } }

    Read the article

  • Buffer Overrun Issues VC++

    - by sijith
    When i execute my code i am getting this error LPTSTR lpBuffer; ::GetLogicalDriveStrings(1024,lpBuffer); while(*lpBuffer != NULL) { printf("%s\n", lpBuffer); // or MessageBox(NULL, temp, "Test", 0); or whatever lpBuffer += lstrlen(lpBuffer)+1; printf("sizeof(lpBuffer) %d\n",lstrlen(lpBuffer)); } OutPut C sizeof(lpBuffer) 3 D sizeof(lpBuffer) 3 E sizeof(lpBuffer) 3 F sizeof(lpBuffer) 0

    Read the article

  • Any pitfalls using char* instead of void* when writing cross platform code?

    - by UberMongoose
    Is there any pitfalls when using char*'s to write cross platform code that does memory access? I'm working on a play memory allocator to better understand how to debug memmory issues. I have come to believe char*'s are preferable because of the ability to do pointer arithmetic and derefernce them over void*'s, is that true? Do the following assumptions always hold true on different common platforms? sizeof(char) == 1 sizeof(char*) == sizeof(void*) sizeof(char*) == sizeof(size_t)

    Read the article

  • Indexed Drawing in OpenGL not working

    - by user2050846
    I am trying to render 2 types of primitives- - points ( a Point Cloud ) - triangles ( a Mesh ) I am rendering points simply without any index arrays and they are getting rendered fine. To render the meshes I am using indexed drawing with the face list array having the indices of the vertices to be rendered as Triangles. Vertices and their corresponding vertex colors are stored in their corresponding buffers. But the indexed drawing command do not draw anything. The code is as follows- Main Display Function: void display() { simple->enable(); simple->bindUniform("MV",modelview); simple->bindUniform("P", projection); // rendering Point Cloud glBindVertexArray(vao); // Vertex buffer Point Cloud glBindBuffer(GL_ARRAY_BUFFER,vertexbuffer); glEnableVertexAttribArray(0); glVertexAttribPointer(0,3,GL_FLOAT,GL_FALSE,0,0); // Color Buffer point Cloud glBindBuffer(GL_ARRAY_BUFFER,colorbuffer); glEnableVertexAttribArray(1); glVertexAttribPointer(1,3,GL_FLOAT,GL_FALSE,0,0); // Render Colored Point Cloud //glDrawArrays(GL_POINTS,0,model->vertexCount); glDisableVertexAttribArray(0); glDisableVertexAttribArray(1); // ---------------- END---------------------// //// Floor Rendering glBindBuffer(GL_ARRAY_BUFFER,fl); glEnableVertexAttribArray(0); glEnableVertexAttribArray(1); glVertexAttribPointer(0,3,GL_FLOAT,GL_FALSE,0,0); glVertexAttribPointer(1,4,GL_FLOAT,GL_FALSE,0,(void *)48); glDrawArrays(GL_QUADS,0,4); glDisableVertexAttribArray(0); glDisableVertexAttribArray(1); // -----------------END---------------------// //Rendering the Meshes //////////// PART OF CODE THAT IS NOT DRAWING ANYTHING //////////////////// glBindVertexArray(vid); for(int i=0;i<NUM_MESHES;i++) { glBindBuffer(GL_ARRAY_BUFFER,mVertex[i]); glEnableVertexAttribArray(0); glEnableVertexAttribArray(1); glVertexAttribPointer(0,3,GL_FLOAT,GL_FALSE,0,0); glVertexAttribPointer(1,3,GL_FLOAT,GL_FALSE,0,(void *)(meshes[i]->vertexCount*sizeof(glm::vec3))); //glDrawArrays(GL_TRIANGLES,0,meshes[i]->vertexCount); glBindBuffer(GL_ELEMENT_ARRAY_BUFFER,mFace[i]); //cout<<gluErrorString(glGetError()); glDrawElements(GL_TRIANGLES,meshes[i]->faceCount*3,GL_FLOAT,(void *)0); glDisableVertexAttribArray(0); glDisableVertexAttribArray(1); } glUseProgram(0); glutSwapBuffers(); glutPostRedisplay(); } Point Cloud Buffer Allocation Initialization: void initGLPointCloud() { glGenBuffers(1,&vertexbuffer); glGenBuffers(1,&colorbuffer); glGenBuffers(1,&fl); //Populates the position buffer glBindBuffer(GL_ARRAY_BUFFER,vertexbuffer); glBufferData(GL_ARRAY_BUFFER, model->vertexCount * sizeof (glm::vec3), &model->positions[0], GL_STATIC_DRAW); //Populates the color buffer glBindBuffer(GL_ARRAY_BUFFER, colorbuffer); glBufferData(GL_ARRAY_BUFFER, model->vertexCount * sizeof (glm::vec3), &model->colors[0], GL_STATIC_DRAW); model->FreeMemory(); // To free the not needed memory, as the data has been already // copied on graphic card, and wont be used again. glBindBuffer(GL_ARRAY_BUFFER,0); } Meshes Buffer Initialization: void initGLMeshes(int i) { glBindBuffer(GL_ARRAY_BUFFER,mVertex[i]); glBufferData(GL_ARRAY_BUFFER,meshes[i]->vertexCount*sizeof(glm::vec3)*2,NULL,GL_STATIC_DRAW); glBufferSubData(GL_ARRAY_BUFFER,0,meshes[i]->vertexCount*sizeof(glm::vec3),&meshes[i]->positions[0]); glBufferSubData(GL_ARRAY_BUFFER,meshes[i]->vertexCount*sizeof(glm::vec3),meshes[i]->vertexCount*sizeof(glm::vec3),&meshes[i]->colors[0]); glBindBuffer(GL_ELEMENT_ARRAY_BUFFER,mFace[i]); glBufferData(GL_ELEMENT_ARRAY_BUFFER,meshes[i]->faceCount*sizeof(glm::vec3), &meshes[i]->faces[0],GL_STATIC_DRAW); meshes[i]->FreeMemory(); //glBindBuffer(GL_ELEMENT_ARRAY_BUFFER,0); } Initialize the Rendering, load and create shader and calls the mesh and PCD initializers. void initRender() { simple= new GLSLShader("shaders/simple.vert","shaders/simple.frag"); //Point Cloud //Sets up VAO glGenVertexArrays(1, &vao); glBindVertexArray(vao); initGLPointCloud(); //floorData glBindBuffer(GL_ARRAY_BUFFER, fl); glBufferData(GL_ARRAY_BUFFER, sizeof(floorData), &floorData[0], GL_STATIC_DRAW); glBindBuffer(GL_ARRAY_BUFFER,0); glBindVertexArray(0); //Meshes for(int i=0;i<NUM_MESHES;i++) { if(i==0) // SET up the new vertex array state for indexed Drawing { glGenVertexArrays(1, &vid); glBindVertexArray(vid); glGenBuffers(NUM_MESHES,mVertex); glGenBuffers(NUM_MESHES,mColor); glGenBuffers(NUM_MESHES,mFace); } initGLMeshes(i); } glEnable(GL_DEPTH_TEST); } Any help would be much appreciated, I have been breaking my head on this problem since 3 days, and still it is unsolved.

    Read the article

  • How to get proper alignment when printing to file

    - by user1067334
    I have this Structure the elements of which that I need to write in a text file struct Stage3ADisplay { int nSlot; char *Item; char *Type; int nIndex; unsigned char attributesMD[17]; //the last character is \0 unsigned char contentsMD[17]; //only for regular files - //the last character is \0 }; buffer = malloc(sizeof(Stage3ADisplayVar[nIterator]->nSlot) + sizeof(Stage3ADisplayVar[nIterator]->Item) + sizeof(Stage3ADisplayVar[nIterator]->Type) + sizeof(Stage3ADisplayVar[nIterator]->nIndex) + sizeof(Stage3ADisplayVar[nIterator]->attributesMD) + sizeof(Stage3ADisplayVar[nIterator]->contentsMD) + 1); sprintf (buffer,"%d %s %s %d %x %x",Stage3ADisplayVar[nIterator]->nSlot, Stage3ADisplayVar[nIterator]->Item,Stage3ADisplayVar[nIterator]->Type,Stage3ADisplayVar[nIterator]->nIndex,Stage3ADisplayVar[nIterator]->attributesMD,Stage3ADisplayVar[nIterator]->contentsMD); How do I make sure the rows in the file are properly aligned. Thank you.

    Read the article

  • how to create multiple tcp connections between server and client

    - by lowcosthighperformance
    I am new in Unix/Linux networking programming, so I have written server-client program in below.In this code there is one socket between client and server, client requests to server, then server responses from 1 to 100 numbers to client. So my question is how can we do this process with 3 socket( tcp connection) without using thread? ( e.g. First socket runs then second runs then third runs then first again .. ) Do you have any suggestion? Thank you client.c int main() { int sock; struct sockaddr_in sa; int ret; char buf[1024]; int x; sock = socket (AF_INET, SOCK_STREAM, 0); bzero (&sa, sizeof(sa)); sa.sin_family = AF_INET; sa.sin_port = htons(SERVER_PORT); inet_pton (AF_INET, SERVER_IP, &sa.sin_addr); ret = connect (sock, (const struct sockaddr *) &sa,sizeof (sa)); if (ret != 0) { printf ("connect failed\n"); exit (0); } x = 0; while (x != -1) { read (sock, buf , sizeof(int)); x = ntohl(*((int *)buf)); if (x != -1) printf ("int rcvd = %d\n", x); } close (sock); exit (0); } server.c int main() { int list_sock; int conn_sock; struct sockaddr_in sa, ca; socklen_t ca_len; char buf[1024]; int i; char ipaddrstr[IPSTRLEN]; list_sock = socket (AF_INET, SOCK_STREAM, 0); bzero (&sa, sizeof(sa)); sa.sin_family = AF_INET; sa.sin_addr.s_addr = htonl(INADDR_ANY); sa.sin_port = htons(SERVER_PORT); bind (list_sock,(struct sockaddr *) &sa,sizeof(sa)); listen (list_sock, 5); while (1){ bzero (&ca, sizeof(ca)); ca_len = sizeof(ca); // important to initialize conn_sock = accept (list_sock,(struct sockaddr *) &ca,&ca_len); printf ("connection from: ip=%s port=%d \n",inet_ntop(AF_INET, &(ca.sin_addr), ipaddrstr, IPSTRLEN),ntohs(ca.sin_port)); for (i=0; i<100; ++i){ *((int *)buf) = htonl(i+20); // we using converting to network byte order write (conn_sock, buf, sizeof(int)); } * ((int *)buf) = htonl(-1); write (conn_sock, buf, sizeof(int)); close (conn_sock); printf ("server closed connection to client\n"); } }

    Read the article

  • how can I specify interleaved vertex attributes and vertex indices

    - by freefallr
    I'm writing a generic ShaderProgram class that compiles a set of Shader objects, passes args to the shader (like vertex position, vertex normal, tex coords etc), then links the shader components into a shader program, for use with glDrawArrays. My vertex data already exists in a VertexBufferObject that uses the following data structure to create a vertex buffer: class CustomVertex { public: float m_Position[3]; // x, y, z // offset 0, size = 3*sizeof(float) float m_TexCoords[2]; // u, v // offset 3*sizeof(float), size = 2*sizeof(float) float m_Normal[3]; // nx, ny, nz; float colour[4]; // r, g, b, a float padding[20]; // padded for performance }; I've already written a working VertexBufferObject class that creates a vertex buffer object from an array of CustomVertex objects. This array is said to be interleaved. It renders successfully with the following code: void VertexBufferObject::Draw() { if( ! m_bInitialized ) return; glBindBuffer( GL_ARRAY_BUFFER, m_nVboId ); glBindBuffer( GL_ELEMENT_ARRAY_BUFFER, m_nVboIdIndex ); glEnableClientState( GL_VERTEX_ARRAY ); glEnableClientState( GL_TEXTURE_COORD_ARRAY ); glEnableClientState( GL_NORMAL_ARRAY ); glEnableClientState( GL_COLOR_ARRAY ); glVertexPointer( 3, GL_FLOAT, sizeof(CustomVertex), ((char*)NULL + 0) ); glTexCoordPointer(3, GL_FLOAT, sizeof(CustomVertex), ((char*)NULL + 12)); glNormalPointer(GL_FLOAT, sizeof(CustomVertex), ((char*)NULL + 20)); glColorPointer(3, GL_FLOAT, sizeof(CustomVertex), ((char*)NULL + 32)); glDrawElements( GL_TRIANGLES, m_nNumIndices, GL_UNSIGNED_INT, ((char*)NULL + 0) ); glDisableClientState( GL_VERTEX_ARRAY ); glDisableClientState( GL_TEXTURE_COORD_ARRAY ); glDisableClientState( GL_NORMAL_ARRAY ); glDisableClientState( GL_COLOR_ARRAY ); glBindBuffer( GL_ARRAY_BUFFER, 0 ); glBindBuffer( GL_ELEMENT_ARRAY_BUFFER, 0 ); } Back to the Vertex Array Object though. My code for creating the Vertex Array object is as follows. This is performed before the ShaderProgram runtime linking stage, and no glErrors are reported after its steps. // Specify the shader arg locations (e.g. their order in the shader code) for( int n = 0; n < vShaderArgs.size(); n ++) glBindAttribLocation( m_nProgramId, n, vShaderArgs[n].sFieldName.c_str() ); // Create and bind to a vertex array object, which stores the relationship between // the buffer and the input attributes glGenVertexArrays( 1, &m_nVaoHandle ); glBindVertexArray( m_nVaoHandle ); // Enable the vertex attribute array (we're using interleaved array, since its faster) glBindBuffer( GL_ARRAY_BUFFER, vShaderArgs[0].nVboId ); glBindBuffer( GL_ELEMENT_ARRAY_BUFFER, vShaderArgs[0].nVboIndexId ); // vertex data for( int n = 0; n < vShaderArgs.size(); n ++ ) { glEnableVertexAttribArray(n); glVertexAttribPointer( n, vShaderArgs[n].nFieldSize, GL_FLOAT, GL_FALSE, vShaderArgs[n].nStride, (GLubyte *) NULL + vShaderArgs[n].nFieldOffset ); AppLog::Ref().OutputGlErrors(); } This doesn't render correctly at all. I get a pattern of white specks onscreen, in the shape of the terrain rectangle, but there are no regular lines etc. Here's the code I use for rendering: void ShaderProgram::Draw() { using namespace AntiMatter; if( ! m_nShaderProgramId || ! m_nVaoHandle ) { AppLog::Ref().LogMsg("ShaderProgram::Draw() Couldn't draw object, as initialization of ShaderProgram is incomplete"); return; } glUseProgram( m_nShaderProgramId ); glBindVertexArray( m_nVaoHandle ); glDrawArrays( GL_TRIANGLES, 0, m_nNumTris ); glBindVertexArray(0); glUseProgram(0); } Can anyone see errors or omissions in either the VAO creation code or rendering code? thanks!

    Read the article

  • CCSpriteHole in cocos2d 2.0?

    - by rakkarage
    i was using this cocos2d class CCSpriteHole in cocos2d 1.0 fine... http://jpsarda.tumblr.com/post/15779708304/new-cocos2d-iphone-extensions-a-progress-bar-and-a i am trying to convert it to cocos2d 2.0... i got it to compile by changing glVertexPointer to glVertexAttribPointer like in the 2.0 version of CCSpriteScale9 here http://jpsarda.tumblr.com/post/9162433577/scale9grid-for-cocos2d and changing contentSizeInPixels_ to contentSize_... -(id) init { if( (self=[super init]) ) { opacityModifyRGB_ = YES; opacity_ = 255; color_ = colorUnmodified_ = ccWHITE; capSize=capSizeInPixels=CGSizeZero; //Not used blendFunc_.src = CC_BLEND_SRC; blendFunc_.dst = CC_BLEND_DST; // update texture (calls updateBlendFunc) [self setTexture:nil]; // default transform anchor anchorPoint_ = ccp(0.5f, 0.5f); vertexDataCount=24; vertexData = (ccV2F_C4F_T2F*) malloc(vertexDataCount * sizeof(ccV2F_C4F_T2F)); [self setTextureRectInPixels:CGRectZero untrimmedSize:CGSizeZero]; } return self; } -(id) initWithTexture:(CCTexture2D*)texture rect:(CGRect)rect { NSAssert(texture!=nil, @"Invalid texture for sprite"); // IMPORTANT: [self init] and not [super init]; if( (self = [self init]) ) { [self setTexture:texture]; [self setTextureRect:rect]; } return self; } -(id) initWithTexture:(CCTexture2D*)texture { NSAssert(texture!=nil, @"Invalid texture for sprite"); CGRect rect = CGRectZero; rect.size = texture.contentSize; return [self initWithTexture:texture rect:rect]; } -(id) initWithFile:(NSString*)filename { NSAssert(filename!=nil, @"Invalid filename for sprite"); CCTexture2D *texture = [[CCTextureCache sharedTextureCache] addImage: filename]; if( texture ) return [self initWithTexture:texture]; return nil; } +(id)spriteWithFile:(NSString*)f { return [[self alloc] initWithFile:f]; } - (void) dealloc { if (vertexData) free(vertexData); } -(void) updateColor { ccColor4F color4; color4.r=(float)color_.r/255.0f; color4.g=(float)color_.g/255.0f; color4.b=(float)color_.b/255.0f; color4.a=(float)opacity_/255.0f; for (int i=0; i<vertexDataCount; i++) { vertexData[i].colors=color4; } } -(void)updateTextureCoords:(CGRect)rect { CCTexture2D *tex = texture_; if(!tex) return; float atlasWidth = (float)tex.pixelsWide; float atlasHeight = (float)tex.pixelsHigh; float left,right,top,bottom; left = rect.origin.x/atlasWidth; right = left + rect.size.width/atlasWidth; top = rect.origin.y/atlasHeight; bottom = top + rect.size.height/atlasHeight; // // |/|/|/| // CGSize capTexCoordsSize=CGSizeMake(capSizeInPixels.width/atlasWidth, capSizeInPixels.height/atlasHeight); // From left to right //Top band // Left vertexData[0].texCoords=(ccTex2F){left,top}; vertexData[1].texCoords=(ccTex2F){left,top+capTexCoordsSize.height}; vertexData[2].texCoords=(ccTex2F){left+capTexCoordsSize.width,top}; vertexData[3].texCoords=(ccTex2F){left+capTexCoordsSize.width,top+capTexCoordsSize.height}; // Center vertexData[4].texCoords=(ccTex2F){right-capTexCoordsSize.width,top}; vertexData[5].texCoords=(ccTex2F){right-capTexCoordsSize.width,top+capTexCoordsSize.height}; // Right vertexData[6].texCoords=(ccTex2F){right,top}; vertexData[7].texCoords=(ccTex2F){right,top+capTexCoordsSize.height}; //Center band // Left vertexData[8].texCoords=(ccTex2F){left,bottom-capTexCoordsSize.height}; vertexData[9].texCoords=(ccTex2F){left,top+capTexCoordsSize.height}; vertexData[10].texCoords=(ccTex2F){left+capTexCoordsSize.width,bottom-capTexCoordsSize.height}; vertexData[11].texCoords=(ccTex2F){left+capTexCoordsSize.width,top+capTexCoordsSize.height}; // Center vertexData[12].texCoords=(ccTex2F){right-capTexCoordsSize.width,bottom-capTexCoordsSize.height}; vertexData[13].texCoords=(ccTex2F){right-capTexCoordsSize.width,top+capTexCoordsSize.height}; // Right vertexData[14].texCoords=(ccTex2F){right,bottom-capTexCoordsSize.height}; vertexData[15].texCoords=(ccTex2F){right,top+capTexCoordsSize.height}; //Bottom band //Left vertexData[16].texCoords=(ccTex2F){left,bottom}; vertexData[17].texCoords=(ccTex2F){left,bottom-capTexCoordsSize.height}; vertexData[18].texCoords=(ccTex2F){left+capTexCoordsSize.width,bottom}; vertexData[19].texCoords=(ccTex2F){left+capTexCoordsSize.width,bottom-capTexCoordsSize.height}; // Center vertexData[20].texCoords=(ccTex2F){right-capTexCoordsSize.width,bottom}; vertexData[21].texCoords=(ccTex2F){right-capTexCoordsSize.width,bottom-capTexCoordsSize.height}; // Right vertexData[22].texCoords=(ccTex2F){right,bottom}; vertexData[23].texCoords=(ccTex2F){right,bottom-capTexCoordsSize.height}; } -(void) updateVertices { float left=0; //-spriteSizeInPixels.width*0.5f; float right=left+contentSize_.width; float bottom=0; //-spriteSizeInPixels.height*0.5f; float top=bottom+contentSize_.height; float holeLeft=holeRect.origin.x*CC_CONTENT_SCALE_FACTOR(); float holeRight=holeLeft+holeRect.size.width*CC_CONTENT_SCALE_FACTOR(); float holeBottom=holeRect.origin.y*CC_CONTENT_SCALE_FACTOR(); float holeTop=holeBottom+holeRect.size.height*CC_CONTENT_SCALE_FACTOR(); // // |/|/|/| // // From left to right //Top band // Left vertexData[0].vertices=(ccVertex2F){left,top}; vertexData[1].vertices=(ccVertex2F){left,holeTop}; vertexData[2].vertices=(ccVertex2F){holeLeft,top}; vertexData[3].vertices=(ccVertex2F){holeLeft,holeTop}; // Center vertexData[4].vertices=(ccVertex2F){holeRight,top}; vertexData[5].vertices=(ccVertex2F){holeRight,holeTop}; // Right vertexData[6].vertices=(ccVertex2F){right,top}; vertexData[7].vertices=(ccVertex2F){right,holeTop}; //Center band // Left vertexData[8].vertices=(ccVertex2F){left,holeBottom}; vertexData[9].vertices=(ccVertex2F){left,holeTop}; vertexData[10].vertices=(ccVertex2F){holeLeft,holeBottom}; vertexData[11].vertices=(ccVertex2F){holeLeft,holeTop}; // Center vertexData[12].vertices=(ccVertex2F){holeRight,holeBottom}; vertexData[13].vertices=(ccVertex2F){holeRight,holeTop}; // Right vertexData[14].vertices=(ccVertex2F){right,holeBottom}; vertexData[15].vertices=(ccVertex2F){right,holeTop}; //Bottom band //Left vertexData[16].vertices=(ccVertex2F){left,bottom}; vertexData[17].vertices=(ccVertex2F){left,holeBottom}; vertexData[18].vertices=(ccVertex2F){holeLeft,bottom}; vertexData[19].vertices=(ccVertex2F){holeLeft,holeBottom}; // Center vertexData[20].vertices=(ccVertex2F){holeRight,bottom}; vertexData[21].vertices=(ccVertex2F){holeRight,holeBottom}; // Right vertexData[22].vertices=(ccVertex2F){right,bottom}; vertexData[23].vertices=(ccVertex2F){right,holeBottom}; } -(void) setHole:(CGRect)r inRect:(CGRect)totalSurface { holeRect=r; self.contentSize=totalSurface.size; holeRect.origin=ccpSub(holeRect.origin,totalSurface.origin); CGPoint holeCenter=ccp(holeRect.origin.x+holeRect.size.width*0.5f,holeRect.origin.y+holeRect.size.height*0.5f); self.anchorPoint=ccp(holeCenter.x/contentSize_.width,holeCenter.y/contentSize_.height); //[self updateTextureCoords:rectInPixels_]; [self updateVertices]; [self updateColor]; } -(void) draw { BOOL newBlend = NO; if( blendFunc_.src != CC_BLEND_SRC || blendFunc_.dst != CC_BLEND_DST ) { newBlend = YES; glBlendFunc( blendFunc_.src, blendFunc_.dst ); } glBindTexture(GL_TEXTURE_2D, [texture_ name]); glVertexAttribPointer(kCCVertexAttrib_Position, 2, GL_FLOAT, GL_FALSE, sizeof(ccV2F_C4F_T2F), &vertexData[0].vertices); glVertexAttribPointer(kCCVertexAttrib_TexCoords, 2, GL_FLOAT, GL_FALSE, sizeof(ccV2F_C4F_T2F), &vertexData[0].texCoords); glVertexAttribPointer(kCCVertexAttrib_Color, 4, GL_FLOAT, GL_FALSE, sizeof(ccV2F_C4F_T2F), &vertexData[0].colors); glDrawArrays(GL_TRIANGLE_STRIP, 0, 8); glVertexAttribPointer(kCCVertexAttrib_Position, 2, GL_FLOAT, GL_FALSE, sizeof(ccV2F_C4F_T2F), &vertexData[8].vertices); glVertexAttribPointer(kCCVertexAttrib_TexCoords, 2, GL_FLOAT, GL_FALSE, sizeof(ccV2F_C4F_T2F), &vertexData[8].texCoords); glVertexAttribPointer(kCCVertexAttrib_Color, 4, GL_FLOAT, GL_FALSE, sizeof(ccV2F_C4F_T2F), &vertexData[8].colors); glDrawArrays(GL_TRIANGLE_STRIP, 0, 8); glVertexAttribPointer(kCCVertexAttrib_Position, 2, GL_FLOAT, GL_FALSE, sizeof(ccV2F_C4F_T2F), &vertexData[16].vertices); glVertexAttribPointer(kCCVertexAttrib_TexCoords, 2, GL_FLOAT, GL_FALSE, sizeof(ccV2F_C4F_T2F), &vertexData[16].texCoords); glVertexAttribPointer(kCCVertexAttrib_Color, 4, GL_FLOAT, GL_FALSE, sizeof(ccV2F_C4F_T2F), &vertexData[16].colors); glDrawArrays(GL_TRIANGLE_STRIP, 0, 8); if( newBlend ) glBlendFunc(CC_BLEND_SRC, CC_BLEND_DST); } -(void)setTextureRectInPixels:(CGRect)rect untrimmedSize:(CGSize)untrimmedSize { rectInPixels_ = rect; rect_ = CC_RECT_PIXELS_TO_POINTS( rect ); //[self setContentSizeInPixels:untrimmedSize]; [self updateTextureCoords:rectInPixels_]; } -(void)setTextureRect:(CGRect)rect { CGRect rectInPixels = CC_RECT_POINTS_TO_PIXELS( rect ); [self setTextureRectInPixels:rectInPixels untrimmedSize:rectInPixels.size]; } // // RGBA protocol // #pragma mark CCSpriteHole - RGBA protocol -(GLubyte) opacity { return opacity_; } -(void) setOpacity:(GLubyte) anOpacity { opacity_ = anOpacity; // special opacity for premultiplied textures if( opacityModifyRGB_ ) [self setColor: (opacityModifyRGB_ ? colorUnmodified_ : color_ )]; [self updateColor]; } - (ccColor3B) color { if(opacityModifyRGB_){ return colorUnmodified_; } return color_; } -(void) setColor:(ccColor3B)color3 { color_ = colorUnmodified_ = color3; if( opacityModifyRGB_ ){ color_.r = color3.r * opacity_/255; color_.g = color3.g * opacity_/255; color_.b = color3.b * opacity_/255; } [self updateColor]; } -(void) setOpacityModifyRGB:(BOOL)modify { ccColor3B oldColor = self.color; opacityModifyRGB_ = modify; self.color = oldColor; } -(BOOL) doesOpacityModifyRGB { return opacityModifyRGB_; } #pragma mark CCSpriteHole - CocosNodeTexture protocol -(void) updateBlendFunc { if( !texture_ || ! [texture_ hasPremultipliedAlpha] ) { blendFunc_.src = GL_SRC_ALPHA; blendFunc_.dst = GL_ONE_MINUS_SRC_ALPHA; [self setOpacityModifyRGB:NO]; } else { blendFunc_.src = CC_BLEND_SRC; blendFunc_.dst = CC_BLEND_DST; [self setOpacityModifyRGB:YES]; } } -(void) setTexture:(CCTexture2D*)texture { // accept texture==nil as argument NSAssert( !texture || [texture isKindOfClass:[CCTexture2D class]], @"setTexture expects a CCTexture2D. Invalid argument"); texture_ = texture; [self updateBlendFunc]; } -(CCTexture2D*) texture { return texture_; } @end but now positioning and scaling seem to not work? and it starts in the wrong position... but changing the opacity still works. so i was wondering if anyone can see why my 2.0 version is not working? or if maybe there is a better way to do a sprite hole with cocos2d/opengl 2.0? shaders? thanks

    Read the article

  • Strange thing on IPv6 multicast program on Windows

    - by zhanglistar
    I have written an ipv6 multicast program on windows xp sp3. But a problem bothers me a lot. The sendto function implies no error, but I can't capture the packet using wireshark. I am sure the filter is right. Thanks in advance. And the code is as follows: #include "stdafx.h" #include <stdio.h> /* for printf() and fprintf() */ #include <winsock2.h> /* for socket(), connect(), sendto(), and recvfrom() */ #include <ws2tcpip.h> /* for ip_mreq */ #include <stdlib.h> /* for atoi() and exit() */ #include <string.h> /* for memset() */ #include <time.h> /* for timestamps */ #include <pcap.h> #include <Iphlpapi.h> #pragma comment(lib, "Ws2_32.lib") #pragma comment(lib, "wpcap.lib") #pragma comment(lib, "Iphlpapi.lib") int _tmain(int argc, _TCHAR* argv[]) { int sfd; int on, length, iResult; WSADATA wsaData; struct addrinfo Hints; struct addrinfo *multicastAddr, *localAddr; char buf[46]; // Initialize Winsock iResult = WSAStartup(MAKEWORD(2, 2), &wsaData); if (iResult != 0) { printf("WSAStartup failed: %d\n", iResult); return 1; } /* Resolve destination address for multicast datagrams */ memset(&Hints, 0, sizeof (Hints)); Hints.ai_family = AF_INET6; Hints.ai_socktype = SOCK_DGRAM; Hints.ai_protocol = IPPROTO_UDP; Hints.ai_flags = AI_NUMERICHOST; iResult = getaddrinfo("FF02::1:2", "547", &Hints, &multicastAddr); if (iResult != 0) { /* error handling */ printf("socket error: %d\n", WSAGetLastError()); return -1; } /* Get a local address with the same family (IPv4 or IPv6) as our multicast group */ Hints.ai_family = multicastAddr->ai_family; Hints.ai_socktype = SOCK_DGRAM; Hints.ai_flags = AI_PASSIVE; /* Return an address we can bind to */ if ( getaddrinfo(NULL, "546", &Hints, &localAddr) != 0 ) { printf("getaddrinfo() failed: %d\n", WSAGetLastError()); exit(-1); } // Create sending socket //sfd = socket (multicastAddr->ai_family, multicastAddr->ai_socktype, multicastAddr->ai_protocol); sfd = socket(AF_INET6, SOCK_DGRAM, IPPROTO_UDP); if (sfd == -1) { printf("socket error: %d\n", WSAGetLastError()); return 0; } /* Bind to the multicast port */ if ( bind(sfd, localAddr->ai_addr, localAddr->ai_addrlen) != 0 ) { printf("bind() failed: %d\n", WSAGetLastError()); exit(-1); } if (multicastAddr->ai_family == AF_INET6 && multicastAddr->ai_addrlen == sizeof(struct sockaddr_in6)) /* IPv6 */ { on = 1; if (setsockopt (sfd, IPPROTO_IPV6, IPV6_MULTICAST_IF, (char *)&on, sizeof (on) /*(char *)&interface_addr, sizeof(interface_addr)*/) == -1) { printf("setsockopt error:%d\n", WSAGetLastError()); return -1; } if (setsockopt (sfd, IPPROTO_IPV6, IPV6_MULTICAST_LOOP, (char *)&on, sizeof (on) /*(char *)&interface_addr, sizeof(interface_addr)*/) == -1) { printf("setsockopt error:%d\n", WSAGetLastError()); return -1; } struct ipv6_mreq multicastRequest; /* Multicast address join structure */ /* Specify the multicast group */ memcpy(&multicastRequest.ipv6mr_multiaddr, &((struct sockaddr_in6*)(multicastAddr->ai_addr))->sin6_addr, sizeof(struct in6_addr)); /* Accept multicast from any interface */ multicastRequest.ipv6mr_interface = 0; /* Join the multicast address */ if ( setsockopt(sfd, IPPROTO_IPV6, IPV6_JOIN_GROUP, (char*) &multicastRequest, sizeof(multicastRequest)) != 0 ) { printf("setsockopt() failed: %d\n", WSAGetLastError()); return -1; } on = 1; if (setsockopt (sfd, IPPROTO_IPV6, IPV6_MULTICAST_IF, (char *)&on, sizeof (on)) == -1) { printf("setsockopt error:%d\n", WSAGetLastError()); return 0; } } memset(buf, 0, sizeof(buf)); strcpy(buf, "hello world"); iResult = sendto(sfd, buf, strlen(buf), 0, (LPSOCKADDR) multicastAddr->ai_addr, multicastAddr->ai_addrlen); if (iResult == SOCKET_ERROR) { printf("setsockopt error:%d\n", WSAGetLastError()); return -1; /* Error handling */ } return 0; }

    Read the article

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