Search Results

Search found 161 results on 7 pages for 'memcpy'.

Page 2/7 | < Previous Page | 1 2 3 4 5 6 7  | Next Page >

  • How do you convert an unsigned int[16] of hexidecimal to an unsigned char array without losing any information?

    - by user1068636
    I have a unsigned int[16] array that when printed out looks like this: 4418703544ED3F688AC208F53343AA59 The code used to print it out is this: for (i = 0; i < 16; i++) printf("%X", CipherBlock[i] / 16), printf("%X",CipherBlock[i] % 16); printf("\n"); I need to pass this unsigned int array "CipherBlock" into a decrypt() method that only takes unsigned char *. How do correctly memcpy everything from the "CipherBlock" array into an unsigned char array without losing information? My understanding is an unsigned int is 4 bytes and unsigned char 1 byte. Since "CipherBlock" is 16 unsigned integers, the total size in bytes = 16 * 4 = 64 bytes. Does this mean my unsigned char[] array needs to be 64 in length? If so, would the following work? unsigned char arr[64] = { '\0' }; memcpy(arr,CipherBlock,64); This does not seem to work. For some reason it only copies the the first byte of "CipherBlock" into "arr". The rest of "arr" is '\0' thereafter.

    Read the article

  • MemSet & MemCopy

    - by pws5068
    I'm writing a memory allocator, and I need a way to store an integer inside of a chunk of memory. This integer will represent the size of the block so I can navigate to the end given the pointer to the beginning. Here's my test example: head_ptr = (char*) malloc(4*1024*1024); // Allocate 4MB memset(head_ptr,12345,sizeof(int)); // Set Address head_ptr = 12345 memcpy(testInt,head_ptr,sizeof(int)); // Set testInt = head_ptr printf("testInt = %i",testInt); This throws a segmentation fault on the second to last line. Does what I'm trying to do make sense? If so, what is the correct approach?

    Read the article

  • Access Violation

    - by Justin
    I've been learning how to NOP functions in C++ or even C but there are very few tutorials online about it. I've been googling for the past few hours now and I'm just stuck. Here is my code. #include <iostream> #include <windows.h> #include <tlhelp32.h> using namespace std; //#define NOP 0x90 byte NOP[] = {0x90}; void enableDebugPrivileges() { HANDLE hcurrent=GetCurrentProcess(); HANDLE hToken; BOOL bret=OpenProcessToken(hcurrent,40,&hToken); LUID luid; bret=LookupPrivilegeValue(NULL,"SeDebugPrivilege",&luid); TOKEN_PRIVILEGES NewState,PreviousState; DWORD ReturnLength; NewState.PrivilegeCount =1; NewState.Privileges[0].Luid =luid; NewState.Privileges[0].Attributes=2; AdjustTokenPrivileges(hToken,FALSE,&NewState,28,&PreviousState,&ReturnLength); } DWORD GetProcId(char* ProcName) { PROCESSENTRY32 pe32; HANDLE hSnapshot = NULL; pe32.dwSize = sizeof( PROCESSENTRY32 ); hSnapshot = CreateToolhelp32Snapshot( TH32CS_SNAPPROCESS, 0 ); if( Process32First( hSnapshot, &pe32 ) ) { do{ if( strcmp( pe32.szExeFile, ProcName ) == 0 ) break; }while( Process32Next( hSnapshot, &pe32 ) ); } if( hSnapshot != INVALID_HANDLE_VALUE ) CloseHandle( hSnapshot ); return pe32.th32ProcessID; } void WriteMem(DWORD Address, void* Value, size_t Size) { DWORD Protect = NULL; VirtualProtect((LPVOID)Address, 3, PAGE_READWRITE, &Protect); memcpy((void*)Address, Value, 3); VirtualProtect((LPVOID)Address, 3, Protect, &Protect); } void nop_(PVOID address, int bytes){ DWORD d, ds; VirtualProtect(address, bytes, PAGE_EXECUTE_READWRITE, &d); memset(address, 144, bytes); VirtualProtect(address,bytes,d,&ds); } void MemCopy(HANDLE pHandle, void* Dest, const void* Src, int Len) { DWORD OldProtect; DWORD OldProtect2; VirtualProtect(Dest, Len, PAGE_EXECUTE_READWRITE, &OldProtect); memcpy(Dest, Src, Len); VirtualProtect(Dest, Len, OldProtect, &OldProtect2); FlushInstructionCache(pHandle, Dest, Len); } int main() { enableDebugPrivileges(); DWORD pid; HANDLE phandle; // Obtain the process ID pid = GetProcId("gr.exe"); if(GetLastError()) { cout << "Error_PID_: " << GetLastError() << endl; system("pause"); return -1; } // Obtain the process handle phandle = OpenProcess(PROCESS_ALL_ACCESS,0,pid); if(GetLastError()) { cout << "Error_HANDLE_: " << GetLastError() << endl; system("pause"); return -1; } // Debug info, 0 = bad cout <<"pid : " << pid << endl; cout <<"HANDLE: " << phandle << endl << endl; system("pause"); // Change value to short iValue = -1; int choice = 0; BYTE * bGodMode = (BYTE *) (0x409A7E); // Lives Address bool hack = true; while(hack) { system("cls"); cout << "What hack?\n0. Exit\n1. Lives\n\n!> "; cin >> choice; switch(choice) { case 0: { hack=false; break; } case 1: // Modify Time cout << "God Mode On\n!> "; // cin >> iValue; // nop_((PVOID)(0x409A7E), 3); // MemCopy(phandle, (PVOID)0x409A7E, &NOP, 1); WriteMem((DWORD)(0x00409A7E), (void*)NOP, sizeof NOP); if(GetLastError()) { cout << "Error: " << GetLastError() << endl; system("pause"); } break; default: cout << "ERROR!\n"; break; } Sleep(100); } system("pause"); return 0; } This is suppose to NOP the DEC function that is 3 bytes long preventing me from losing lives. However each time I try it, it crashes the hack and says I had a access violation. I tried to look up the reasons and most of them dealt with with the size of the location I'm writing to and what I'm copying from. Otherwise, I have absolutely no idea. Any help would be nice. The game is GunRoar and the base address "0x409A7E" is where the DEC function is.

    Read the article

  • C Programming. How to deep copy a struct?

    - by user69514
    I have the following two structs where "child struct" has a "rusage struct" as an element. Then I create two structs of type "child" let's call them childA and childB How do I copy just the rusage struct from childA to childB? typedef struct{ int numb; char *name; pid_t pid; long userT; long systemT; struct rusage usage; }child; typedef struct{ struct timeval ru_utime; /* user time used */ struct timeval ru_stime; /* system time used */ long ru_maxrss; /* maximum resident set size */ long ru_ixrss; /* integral shared memory size */ long ru_idrss; /* integral unshared data size */ long ru_isrss; /* integral unshared stack size */ long ru_minflt; /* page reclaims */ long ru_majflt; /* page faults */ long ru_nswap; /* swaps */ long ru_inblock; /* block input operations */ long ru_oublock; /* block output operations */ long ru_msgsnd; /* messages sent */ long ru_msgrcv; /* messages received */ long ru_nsignals; /* signals received */ long ru_nvcsw; /* voluntary context switches */ long ru_nivcsw; /* involuntary context switches */ }rusage; I did the following, but I guess it copies the memory location, because if I changed the value of usage in childA, it also changes in childB. memcpy(&childA,&childB, sizeof(rusage)); I know that gives childB all the values from childA. I have already taken care of the others fields in childB, I just need to be able to copy the rusage struct called usage that resides in the "child" struct.

    Read the article

  • C strange array behaviour

    - by LukeN
    After learning that both strncmp is not what it seems to be and strlcpy not being available on my operating system (Linux), I figured I could try and write it myself. I found a quote from Ulrich Drepper, the libc maintainer, who posted an alternative to strlcpy using mempcpy. I don't have mempcpy either, but it's behaviour was easy to replicate. First of, this is the testcase I have #include <stdio.h> #include <string.h> #define BSIZE 10 void insp(const char* s, int n) { int i; for (i = 0; i < n; i++) printf("%c ", s[i]); printf("\n"); for (i = 0; i < n; i++) printf("%02X ", s[i]); printf("\n"); return; } int copy_string(char *dest, const char *src, int n) { int r = strlen(memcpy(dest, src, n-1)); dest[r] = 0; return r; } int main() { char b[BSIZE]; memset(b, 0, BSIZE); printf("Buffer size is %d", BSIZE); insp(b, BSIZE); printf("\nFirst copy:\n"); copy_string(b, "First", BSIZE); insp(b, BSIZE); printf("b = '%s'\n", b); printf("\nSecond copy:\n"); copy_string(b, "Second", BSIZE); insp(b, BSIZE); printf("b = '%s'\n", b); return 0; } And this is its result: Buffer size is 10 00 00 00 00 00 00 00 00 00 00 First copy: F i r s t b = 46 69 72 73 74 00 62 20 3D 00 b = 'First' Second copy: S e c o n d 53 65 63 6F 6E 64 00 00 01 00 b = 'Second' You can see in the internal representation (the lines insp() created) that there's some noise mixed in, like the printf() format string in the inspection after the first copy, and a foreign 0x01 in the second copy. The strings are copied intact and it correctly handles too long source strings (let's ignore the possible issue with passing 0 as length to copy_string for now, I'll fix that later). But why are there foreign array contents (from the format string) inside my destination? It's as if the destination was actually RESIZED to match the new length.

    Read the article

  • Time gaps between host clEnqueue_xxx calls

    - by dialer
    Consider these OpenCL calls (3 memcpy DtoH, 4313 cl_float elements each): clEnqueueReadBuffer(CommandQueue, SpectrumAbsMem, CL_FALSE, 0, SpectrumMemSize, SpectrumAbs, 0, NULL, NULL); clEnqueueReadBuffer(CommandQueue, SpectrumReMem, CL_FALSE, 0, SpectrumMemSize, SpectrumRe, 0, NULL, NULL); clEnqueueReadBuffer(CommandQueue, SpectrumImMem, CL_FALSE, 0, SpectrumMemSize, SpectrumIm, 0, NULL, NULL); When I analyze these with the NVIDIA visual profiler, I see that the actual memcpy operation only takes 8 us, but there is a significant gap of around 130 us after each memcpy. I'm already using the supposedly asynchronous method (the CL_FALSE in the argument list). When I use only one operation, but with three times the size, the operation is way faster. Why is the time gap between the actual memcpy operations so huge, whereas the gap between the kernel execution (exactly before these three operations) and the first memcpy is only 7us? Can I get rid of it, or do I need to accumulate more data before starting a memcpy? If so, is there a convenient way how I could combine mutliple arrays into a single contiguous block of memory, but still have a cl_mem object as a separate device memory pointer to each section?

    Read the article

  • The View-Matrix and Alternative Calculations

    - by P. Avery
    I'm working on a radiosity processor in DirectX 9. The process requires that the camera be placed at the center of a mesh face and a 'screenshot' be taken facing 5 different directions...forward...up...down...left...right... ...The problem is that when the mesh face is facing up( look vector: 0, 1, 0 )...a view matrix cannot be determined using standard trigonometry functions: Matrix4 LookAt( Vector3 eye, Vector3 target, Vector3 up ) { // The "look-at" vector. Vector3 zaxis = normal(target - eye); // The "right" vector. Vector3 xaxis = normal(cross(up, zaxis)); // The "up" vector. Vector3 yaxis = cross(zaxis, xaxis); // Create a 4x4 orientation matrix from the right, up, and at vectors Matrix4 orientation = { xaxis.x, yaxis.x, zaxis.x, 0, xaxis.y, yaxis.y, zaxis.y, 0, xaxis.z, yaxis.z, zaxis.z, 0, 0, 0, 0, 1 }; // Create a 4x4 translation matrix by negating the eye position. Matrix4 translation = { 1, 0, 0, 0, 0, 1, 0, 0, 0, 0, 1, 0, -eye.x, -eye.y, -eye.z, 1 }; // Combine the orientation and translation to compute the view matrix return ( translation * orientation ); } The above function comes from http://3dgep.com/?p=1700... ...Is there a mathematical approach to this problem? Edit: A problem occurs when setting the view matrix to up or down directions, here is an example of the problem when facing down: D3DXVECTOR4 vPos( 3, 3, 3, 1 ), vEye( 1.5, 3, 3, 1 ), vLook( 0, -1, 0, 1 ), vRight( 1, 0, 0, 1 ), vUp( 0, 0, 1, 1 ); D3DXMATRIX mV, mP; D3DXMatrixPerspectiveFovLH( &mP, D3DX_PI / 2, 1, 0.5f, 2000.0f ); D3DXMatrixIdentity( &mV ); memcpy( ( void* )&mV._11, ( void* )&vRight, sizeof( D3DXVECTOR3 ) ); memcpy( ( void* )&mV._21, ( void* )&vUp, sizeof( D3DXVECTOR3 ) ); memcpy( ( void* )&mV._31, ( void* )&vLook, sizeof( D3DXVECTOR3 ) ); memcpy( ( void* )&mV._41, ( void* )&(-vEye), sizeof( D3DXVECTOR3 ) ); D3DXVec4Transform( &vPos, &vPos, &( mV * mP ) ); Results: vPos = D3DXVECTOR3( 1.5, -6, -0.5, 0 ) - this vertex is not properly processed by shader as the homogenous w value is 0 it cannot be normalized to a position within device space...

    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

  • Making swap faster, easier to use and exception-safe

    - by FredOverflow
    I could not sleep last night and started thinking about std::swap. Here is the familiar C++98 version: template <typename T> void swap(T& a, T& b) { T c(a); a = b; b = c; } If a user-defined class Foo uses external ressources, this is inefficient. The common idiom is to provide a method void Foo::swap(Foo& other) and a specialization of std::swap<Foo>. Note that this does not work with class templates since you cannot partially specialize a function template, and overloading names in the std namespace is illegal. The solution is to write a template function in one's own namespace and rely on argument dependent lookup to find it. This depends critically on the client to follow the "using std::swap idiom" instead of calling std::swap directly. Very brittle. In C++0x, if Foo has a user-defined move constructor and a move assignment operator, providing a custom swap method and a std::swap<Foo> specialization has little to no performance benefit, because the C++0x version of std::swap uses efficient moves instead of copies: #include <utility> template <typename T> void swap(T& a, T& b) { T c(std::move(a)); a = std::move(b); b = std::move(c); } Not having to fiddle with swap anymore already takes a lot of burden away from the programmer. Current compilers do not generate move constructors and move assignment operators automatically yet, but as far as I know, this will change. The only problem left then is exception-safety, because in general, move operations are allowed to throw, and this opens up a whole can of worms. The question "What exactly is the state of a moved-from object?" complicates things further. Then I was thinking, what exactly are the semantics of std::swap in C++0x if everything goes fine? What is the state of the objects before and after the swap? Typically, swapping via move operations does not touch external resources, only the "flat" object representations themselves. So why not simply write a swap template that does exactly that: swap the object representations? #include <cstring> template <typename T> void swap(T& a, T& b) { unsigned char c[sizeof(T)]; memcpy( c, &a, sizeof(T)); memcpy(&a, &b, sizeof(T)); memcpy(&b, c, sizeof(T)); } This is as efficient as it gets: it simply blasts through raw memory. It does not require any intervention from the user: no special swap methods or move operations have to be defined. This means that it even works in C++98 (which does not have rvalue references, mind you). But even more importantly, we can now forget about the exception-safety issues, because memcpy never throws. I can see two potential problems with this approach: First, not all objects are meant to be swapped. If a class designer hides the copy constructor or the copy assignment operator, trying to swap objects of the class should fail at compile-time. We can simply introduce some dead code that checks whether copying and assignment are legal on the type: template <typename T> void swap(T& a, T& b) { if (false) // dead code, never executed { T c(a); // copy-constructible? a = b; // assignable? } unsigned char c[sizeof(T)]; std::memcpy( c, &a, sizeof(T)); std::memcpy(&a, &b, sizeof(T)); std::memcpy(&b, c, sizeof(T)); } Any decent compiler can trivially get rid of the dead code. (There are probably better ways to check the "swap conformance", but that is not the point. What matters is that it's possible). Second, some types might perform "unusual" actions in the copy constructor and copy assignment operator. For example, they might notify observers of their change. I deem this a minor issue, because such kinds of objects probably should not have provided copy operations in the first place. Please let me know what you think of this approach to swapping. Would it work in practice? Would you use it? Can you identify library types where this would break? Do you see additional problems? Discuss!

    Read the article

  • Convert from float to QByteArray

    - by radix07
    Is there a quick way to convert a float value to a byte wise (hex) representation in a QByteArray? Have done similar with memcpy() before using arrays, but this doesn't seem to work too well with QByteArray. For example: memcpy(&byteArrayData,&floatData,sizeof(float)); Can go the other way just fine using: float *value= (float *)byteArrayData.data(); Am I just implementing this wrong or is there a better way to do it using Qt? Thanks

    Read the article

  • gdb reverse debugging error

    - by Werner
    Hi, i started to try reverse debugging with gdb 7, followin the tutorial: http://www.sourceware.org/gdb/wiki/ProcessRecord/Tutorial and I thought, great! Then I started to debug a real program which gives an error at the end. So I run it with gdb, and I put a breakpoint just before the place I think the error appears. Then I type "record" in order to start to recrd actions for future reverse-debugging. But after some steps I get Process record doesn't support instruction 0xf0d at address 0x2aaaab4c4b4e. Process record: failed to record execution log. Program received signal SIGTRAP, Trace/breakpoint trap. 0x00002aaaab4c4b4e in memcpy () from /lib64/libc.so.6 (gdb) n Single stepping until exit from function memcpy, which has no line number information. Process record doesn't support instruction 0xf0d at address 0x2aaaab4c4b4e. Process record: failed to record execution log. Program received signal SIGABRT, Aborted. 0x00002aaaab4c4b4e in memcpy () from /lib64/libc.so.6 Before I look at in in detail, I wonder if this feature is still buggy, or if I should start to record from the beginning. Where this "record" error happens, just an object is created as a copy of other: Thanks

    Read the article

  • Conceal packet loss in PCM stream

    - by ZeroDefect
    I am looking to use 'Packet Loss Concealment' to conceal lost PCM frames in an audio stream. Unfortunately, I cannot find a library that is accessible without all the licensing restrictions and code bloat (...up for some suggestions though). I have located some GPL code written by Steve Underwood for the Asterisk project which implements PLC. There are several limitations; although, as Steve suggests in his code, his algorithm can be applied to different streams with a bit of work. Currently, the code works with 8kHz 16-bit signed mono streams. Variations of the code can be found through a simple search of Google Code Search. My hope is that I can adapt the code to work with other streams. Initially, the goal is to adjust the algorithm for 8+ kHz, 16-bit signed, multichannel audio (all in a C++ environment). Eventually, I'm looking to make the code available under the GPL license in hopes that it could be of benefit to others... Attached is the code below with my efforts. The code includes a main function that will "drop" a number of frames with a given probability. Unfortunately, the code does not quite work as expected. I'm receiving EXC_BAD_ACCESS when running in gdb, but I don't get a trace from gdb when using 'bt' command. Clearly, I'm trampimg on memory some where but not sure exactly where. When I comment out the *amdf_pitch* function, the code runs without crashing... int main (int argc, char *argv[]) { std::ifstream fin("C:\\cc32kHz.pcm"); if(!fin.is_open()) { std::cout << "Failed to open input file" << std::endl; return 1; } std::ofstream fout_repaired("C:\\cc32kHz_repaired.pcm"); if(!fout_repaired.is_open()) { std::cout << "Failed to open output repaired file" << std::endl; return 1; } std::ofstream fout_lossy("C:\\cc32kHz_lossy.pcm"); if(!fout_lossy.is_open()) { std::cout << "Failed to open output repaired file" << std::endl; return 1; } audio::PcmConcealer Concealer; Concealer.Init(1, 16, 32000); //Generate random numbers; srand( time(NULL) ); int value = 0; int probability = 5; while(!fin.eof()) { char arr[2]; fin.read(arr, 2); //Generate's random number; value = rand() % 100 + 1; if(value <= probability) { char blank[2] = {0x00, 0x00}; fout_lossy.write(blank, 2); //Fill in data; Concealer.Fill((int16_t *)blank, 1); fout_repaired.write(blank, 2); } else { //Write data to file; fout_repaired.write(arr, 2); fout_lossy.write(arr, 2); Concealer.Receive((int16_t *)arr, 1); } } fin.close(); fout_repaired.close(); fout_lossy.close(); return 0; } PcmConcealer.hpp /* * Code adapted from Steve Underwood of the Asterisk Project. This code inherits * the same licensing restrictions as the Asterisk Project. */ #ifndef __PCMCONCEALER_HPP__ #define __PCMCONCEALER_HPP__ /** 1. What does it do? The packet loss concealment module provides a suitable synthetic fill-in signal, to minimise the audible effect of lost packets in VoIP applications. It is not tied to any particular codec, and could be used with almost any codec which does not specify its own procedure for packet loss concealment. Where a codec specific concealment procedure exists, the algorithm is usually built around knowledge of the characteristics of the particular codec. It will, therefore, generally give better results for that particular codec than this generic concealer will. 2. How does it work? While good packets are being received, the plc_rx() routine keeps a record of the trailing section of the known speech signal. If a packet is missed, plc_fillin() is called to produce a synthetic replacement for the real speech signal. The average mean difference function (AMDF) is applied to the last known good signal, to determine its effective pitch. Based on this, the last pitch period of signal is saved. Essentially, this cycle of speech will be repeated over and over until the real speech resumes. However, several refinements are needed to obtain smooth pleasant sounding results. - The two ends of the stored cycle of speech will not always fit together smoothly. This can cause roughness, or even clicks, at the joins between cycles. To soften this, the 1/4 pitch period of real speech preceeding the cycle to be repeated is blended with the last 1/4 pitch period of the cycle to be repeated, using an overlap-add (OLA) technique (i.e. in total, the last 5/4 pitch periods of real speech are used). - The start of the synthetic speech will not always fit together smoothly with the tail of real speech passed on before the erasure was identified. Ideally, we would like to modify the last 1/4 pitch period of the real speech, to blend it into the synthetic speech. However, it is too late for that. We could have delayed the real speech a little, but that would require more buffer manipulation, and hurt the efficiency of the no-lost-packets case (which we hope is the dominant case). Instead we use a degenerate form of OLA to modify the start of the synthetic data. The last 1/4 pitch period of real speech is time reversed, and OLA is used to blend it with the first 1/4 pitch period of synthetic speech. The result seems quite acceptable. - As we progress into the erasure, the chances of the synthetic signal being anything like correct steadily fall. Therefore, the volume of the synthesized signal is made to decay linearly, such that after 50ms of missing audio it is reduced to silence. - When real speech resumes, an extra 1/4 pitch period of sythetic speech is blended with the start of the real speech. If the erasure is small, this smoothes the transition. If the erasure is long, and the synthetic signal has faded to zero, the blending softens the start up of the real signal, avoiding a kind of "click" or "pop" effect that might occur with a sudden onset. 3. How do I use it? Before audio is processed, call plc_init() to create an instance of the packet loss concealer. For each received audio packet that is acceptable (i.e. not including those being dropped for being too late) call plc_rx() to record the content of the packet. Note this may modify the packet a little after a period of packet loss, to blend real synthetic data smoothly. When a real packet is not available in time, call plc_fillin() to create a sythetic substitute. That's it! */ /*! Minimum allowed pitch (66 Hz) */ #define PLC_PITCH_MIN(SAMPLE_RATE) ((double)(SAMPLE_RATE) / 66.6) /*! Maximum allowed pitch (200 Hz) */ #define PLC_PITCH_MAX(SAMPLE_RATE) ((SAMPLE_RATE) / 200) /*! Maximum pitch OLA window */ //#define PLC_PITCH_OVERLAP_MAX(SAMPLE_RATE) ((PLC_PITCH_MIN(SAMPLE_RATE)) >> 2) /*! The length over which the AMDF function looks for similarity (20 ms) */ #define CORRELATION_SPAN(SAMPLE_RATE) ((20 * (SAMPLE_RATE)) / 1000) /*! History buffer length. The buffer must also be at leat 1.25 times PLC_PITCH_MIN, but that is much smaller than the buffer needs to be for the pitch assessment. */ //#define PLC_HISTORY_LEN(SAMPLE_RATE) ((CORRELATION_SPAN(SAMPLE_RATE)) + (PLC_PITCH_MIN(SAMPLE_RATE))) namespace audio { typedef struct { /*! Consecutive erased samples */ int missing_samples; /*! Current offset into pitch period */ int pitch_offset; /*! Pitch estimate */ int pitch; /*! Buffer for a cycle of speech */ float *pitchbuf;//[PLC_PITCH_MIN]; /*! History buffer */ short *history;//[PLC_HISTORY_LEN]; /*! Current pointer into the history buffer */ int buf_ptr; } plc_state_t; class PcmConcealer { public: PcmConcealer(); ~PcmConcealer(); void Init(int channels, int bit_depth, int sample_rate); //Process a block of received audio samples. int Receive(short amp[], int frames); //Fill-in a block of missing audio samples. int Fill(short amp[], int frames); void Destroy(); private: int amdf_pitch(int min_pitch, int max_pitch, short amp[], int channel_index, int frames); void save_history(plc_state_t *s, short *buf, int channel_index, int frames); void normalise_history(plc_state_t *s); /** Holds the states of each of the channels **/ std::vector< plc_state_t * > ChannelStates; int plc_pitch_min; int plc_pitch_max; int plc_pitch_overlap_max; int correlation_span; int plc_history_len; int channel_count; int sample_rate; bool Initialized; }; } #endif PcmConcealer.cpp /* * Code adapted from Steve Underwood of the Asterisk Project. This code inherits * the same licensing restrictions as the Asterisk Project. */ #include "audio/PcmConcealer.hpp" /* We do a straight line fade to zero volume in 50ms when we are filling in for missing data. */ #define ATTENUATION_INCREMENT 0.0025 /* Attenuation per sample */ #if !defined(INT16_MAX) #define INT16_MAX (32767) #define INT16_MIN (-32767-1) #endif #ifdef WIN32 inline double rint(double x) { return floor(x + 0.5); } #endif inline short fsaturate(double damp) { if (damp > 32767.0) return INT16_MAX; if (damp < -32768.0) return INT16_MIN; return (short)rint(damp); } namespace audio { PcmConcealer::PcmConcealer() : Initialized(false) { } PcmConcealer::~PcmConcealer() { Destroy(); } void PcmConcealer::Init(int channels, int bit_depth, int sample_rate) { if(Initialized) return; if(channels <= 0 || bit_depth != 16) return; Initialized = true; channel_count = channels; this->sample_rate = sample_rate; ////////////// double min = PLC_PITCH_MIN(sample_rate); int imin = (int)min; double max = PLC_PITCH_MAX(sample_rate); int imax = (int)max; plc_pitch_min = imin; plc_pitch_max = imax; plc_pitch_overlap_max = (plc_pitch_min >> 2); correlation_span = CORRELATION_SPAN(sample_rate); plc_history_len = correlation_span + plc_pitch_min; ////////////// for(int i = 0; i < channel_count; i ++) { plc_state_t *t = new plc_state_t; memset(t, 0, sizeof(plc_state_t)); t->pitchbuf = new float[plc_pitch_min]; t->history = new short[plc_history_len]; ChannelStates.push_back(t); } } void PcmConcealer::Destroy() { if(!Initialized) return; while(ChannelStates.size()) { plc_state_t *s = ChannelStates.at(0); if(s) { if(s->history) delete s->history; if(s->pitchbuf) delete s->pitchbuf; memset(s, 0, sizeof(plc_state_t)); delete s; } ChannelStates.erase(ChannelStates.begin()); } ChannelStates.clear(); Initialized = false; } //Process a block of received audio samples. int PcmConcealer::Receive(short amp[], int frames) { if(!Initialized) return 0; int j = 0; for(int k = 0; k < ChannelStates.size(); k++) { int i; int overlap_len; int pitch_overlap; float old_step; float new_step; float old_weight; float new_weight; float gain; plc_state_t *s = ChannelStates.at(k); if (s->missing_samples) { /* Although we have a real signal, we need to smooth it to fit well with the synthetic signal we used for the previous block */ /* The start of the real data is overlapped with the next 1/4 cycle of the synthetic data. */ pitch_overlap = s->pitch >> 2; if (pitch_overlap > frames) pitch_overlap = frames; gain = 1.0 - s->missing_samples * ATTENUATION_INCREMENT; if (gain < 0.0) gain = 0.0; new_step = 1.0/pitch_overlap; old_step = new_step*gain; new_weight = new_step; old_weight = (1.0 - new_step)*gain; for (i = 0; i < pitch_overlap; i++) { int index = (i * channel_count) + j; amp[index] = fsaturate(old_weight * s->pitchbuf[s->pitch_offset] + new_weight * amp[index]); if (++s->pitch_offset >= s->pitch) s->pitch_offset = 0; new_weight += new_step; old_weight -= old_step; if (old_weight < 0.0) old_weight = 0.0; } s->missing_samples = 0; } save_history(s, amp, j, frames); j++; } return frames; } //Fill-in a block of missing audio samples. int PcmConcealer::Fill(short amp[], int frames) { if(!Initialized) return 0; int j =0; for(int k = 0; k < ChannelStates.size(); k++) { short *tmp = new short[plc_pitch_overlap_max]; int i; int pitch_overlap; float old_step; float new_step; float old_weight; float new_weight; float gain; short *orig_amp; int orig_len; orig_amp = amp; orig_len = frames; plc_state_t *s = ChannelStates.at(k); if (s->missing_samples == 0) { // As the gap in real speech starts we need to assess the last known pitch, //and prepare the synthetic data we will use for fill-in normalise_history(s); s->pitch = amdf_pitch(plc_pitch_min, plc_pitch_max, s->history + plc_history_len - correlation_span - plc_pitch_min, j, correlation_span); // We overlap a 1/4 wavelength pitch_overlap = s->pitch >> 2; // Cook up a single cycle of pitch, using a single of the real signal with 1/4 //cycle OLA'ed to make the ends join up nicely // The first 3/4 of the cycle is a simple copy for (i = 0; i < s->pitch - pitch_overlap; i++) s->pitchbuf[i] = s->history[plc_history_len - s->pitch + i]; // The last 1/4 of the cycle is overlapped with the end of the previous cycle new_step = 1.0/pitch_overlap; new_weight = new_step; for ( ; i < s->pitch; i++) { s->pitchbuf[i] = s->history[plc_history_len - s->pitch + i]*(1.0 - new_weight) + s->history[plc_history_len - 2*s->pitch + i]*new_weight; new_weight += new_step; } // We should now be ready to fill in the gap with repeated, decaying cycles // of what is in pitchbuf // We need to OLA the first 1/4 wavelength of the synthetic data, to smooth // it into the previous real data. To avoid the need to introduce a delay // in the stream, reverse the last 1/4 wavelength, and OLA with that. gain = 1.0; new_step = 1.0/pitch_overlap; old_step = new_step; new_weight = new_step; old_weight = 1.0 - new_step; for (i = 0; i < pitch_overlap; i++) { int index = (i * channel_count) + j; amp[index] = fsaturate(old_weight * s->history[plc_history_len - 1 - i] + new_weight * s->pitchbuf[i]); new_weight += new_step; old_weight -= old_step; if (old_weight < 0.0) old_weight = 0.0; } s->pitch_offset = i; } else { gain = 1.0 - s->missing_samples*ATTENUATION_INCREMENT; i = 0; } for ( ; gain > 0.0 && i < frames; i++) { int index = (i * channel_count) + j; amp[index] = s->pitchbuf[s->pitch_offset]*gain; gain -= ATTENUATION_INCREMENT; if (++s->pitch_offset >= s->pitch) s->pitch_offset = 0; } for ( ; i < frames; i++) { int index = (i * channel_count) + j; amp[i] = 0; } s->missing_samples += orig_len; save_history(s, amp, j, frames); delete [] tmp; j++; } return frames; } void PcmConcealer::save_history(plc_state_t *s, short *buf, int channel_index, int frames) { if (frames >= plc_history_len) { /* Just keep the last part of the new data, starting at the beginning of the buffer */ //memcpy(s->history, buf + len - plc_history_len, sizeof(short)*plc_history_len); int frames_to_copy = plc_history_len; for(int i = 0; i < frames_to_copy; i ++) { int index = (channel_count * (i + frames - plc_history_len)) + channel_index; s->history[i] = buf[index]; } s->buf_ptr = 0; return; } if (s->buf_ptr + frames > plc_history_len) { /* Wraps around - must break into two sections */ //memcpy(s->history + s->buf_ptr, buf, sizeof(short)*(plc_history_len - s->buf_ptr)); short *hist_ptr = s->history + s->buf_ptr; int frames_to_copy = plc_history_len - s->buf_ptr; for(int i = 0; i < frames_to_copy; i ++) { int index = (channel_count * i) + channel_index; hist_ptr[i] = buf[index]; } frames -= (plc_history_len - s->buf_ptr); //memcpy(s->history, buf + (plc_history_len - s->buf_ptr), sizeof(short)*len); frames_to_copy = frames; for(int i = 0; i < frames_to_copy; i ++) { int index = (channel_count * (i + (plc_history_len - s->buf_ptr))) + channel_index; s->history[i] = buf[index]; } s->buf_ptr = frames; return; } /* Can use just one section */ //memcpy(s->history + s->buf_ptr, buf, sizeof(short)*len); short *hist_ptr = s->history + s->buf_ptr; int frames_to_copy = frames; for(int i = 0; i < frames_to_copy; i ++) { int index = (channel_count * i) + channel_index; hist_ptr[i] = buf[index]; } s->buf_ptr += frames; } void PcmConcealer::normalise_history(plc_state_t *s) { short *tmp = new short[plc_history_len]; if (s->buf_ptr == 0) return; memcpy(tmp, s->history, sizeof(short)*s->buf_ptr); memcpy(s->history, s->history + s->buf_ptr, sizeof(short)*(plc_history_len - s->buf_ptr)); memcpy(s->history + plc_history_len - s->buf_ptr, tmp, sizeof(short)*s->buf_ptr); s->buf_ptr = 0; delete [] tmp; } int PcmConcealer::amdf_pitch(int min_pitch, int max_pitch, short amp[], int channel_index, int frames) { int i; int j; int acc; int min_acc; int pitch; pitch = min_pitch; min_acc = INT_MAX; for (i = max_pitch; i <= min_pitch; i++) { acc = 0; for (j = 0; j < frames; j++) { int index1 = (channel_count * (i+j)) + channel_index; int index2 = (channel_count * j) + channel_index; //std::cout << "Index 1: " << index1 << ", Index 2: " << index2 << std::endl; acc += abs(amp[index1] - amp[index2]); } if (acc < min_acc) { min_acc = acc; pitch = i; } } std::cout << "Pitch: " << pitch << std::endl; return pitch; } } P.S. - I must confess that digital audio is not my forte...

    Read the article

  • In C, is it possible do free only an array first ou last position?

    - by user354959
    Hi there! I've an array, but I don't need its first (or last) position. So I point a new variable to the rest of the array, but I should free the array first/last position. For instance: p = read_csv_file(); q = p + 1; // I don't need the first CSV file field // Here I'd like to free only the first position of p return q; Otherwise I've to memcpy the array to other variable, excluding the first position, and then free the original array. Like this: p = read_csv_file(); q = (int*) malloc(sizeof(int) * (SOME_SIZE - 1)); memcpy(q, p+1, sizeof(int) * (SOME_SIZE - 1)); free(p); return q; But then I'll have the overhead of copying all the array. Is this possible to only free a single position of an array?

    Read the article

  • when to use strncpy or memmove

    - by robUK
    Hello, gcc 4.4.4 c89 I have always used strncpy to copy strings. I have never really used memmove or memcpy very much. However, I am just wondering when would you decide whether to use strncpy, memmove, or memcpy? The code I am writing is for a client/server application. In the documentation they use bcopy. However, could I do the same with the others? bcopy((char*)server->h_addr, (char*)&serv_addr.sin_addr.s_addr, server->h_length); Many thanks,

    Read the article

  • Segmentation fault before return

    - by donalmg
    Hi, Why does the following code seg fault before returning: int main() { char iD[20]; memset (iD, 0, 20); char* prefix; srand (time(NULL) ); int iPrefix = rand()%1000000; sprintf(prefix, "%i", iPrefix); int len = strlen(prefix); char* staticChar = "123456789"; //set prefix into ID memcpy(iD, prefix, len); // append static value memcpy(iD+len, staticChar, 20-len); cout << "END " << endl; return 0; } At the minute, the cout will display, but I get a segmentation fault.

    Read the article

  • In C, is it possible do free only an array first or last position?

    - by user354959
    Hi there! I've an array, but I don't need its first (or last) position. So I point a new variable to the rest of the array, but I should free the array first/last position. For instance: p = read_csv_file(); q = p + 1; // I don't need the first CSV file field // Here I'd like to free only the first position of p return q; Otherwise I've to memcpy the array to other variable, excluding the first position, and then free the original array. Like this: p = read_csv_file(); q = (int*) malloc(sizeof(int) * (SOME_SIZE - 1)); memcpy(q, p+1, sizeof(int) * (SOME_SIZE - 1)); free(p); return q; But then I'll have the overhead of copying all the array. Is this possible to only free a single position of an array?

    Read the article

  • How to fill a structure when a pointer to it, is passed as an argument to a function

    - by Ram
    I have a function: func (struct passwd* pw) { struct passwd* temp; struct passwd* save; temp = getpwnam("someuser"); /* since getpwnam returns a pointer to a static * data buffer, I am copying the returned struct * to a local struct. */ if(temp) { save = malloc(sizeof *save); if (save) { memcpy(save, temp, sizeof(struct passwd)); /* Here, I have to update passed pw* with this save struct. */ *pw = *save; /* (~ memcpy) */ } } } The function which calls func(pw) is able to get the updated information. But is it fine to use it as above. The statement *pw = *save is not a deep copy. I do not want to copy each and every member of structure one by one like pw-pw_shell = strdup(save-pw_shell) etc. Is there any better way to do it? Thanks.

    Read the article

  • Uploading image to flicker in c++

    - by Alien01
    I am creating an application in VC++ using win32,wininet to upload an image to Flickr.I am able to get Frob,Token correctly but when I try to upload the image I am getting error Post size too large. Headers are created as follows wstring wstrAddHeaders = L"Content-Type: multipart/form-data;boundary=ABCD\r\n"; wstrAddHeaders += L"Host: api.flickr.com\r\n"; wchar_t tempStr[MAX_PATH]; wsprintf(L"Content-Length: %ld\r\n",szTotalSize); wstrAddHeaders += tmpStr; wstrAddHeaders +=L"\r\n"; HINTERNET hSession = InternetConnect(hInternet, L"www.flickr.com", INTERNET_DEFAULT_HTTP_PORT, NULL,NULL, INTERNET_SERVICE_HTTP, 0, 0); if(hSession==NULL) { dwErr = GetLastError(); return; } Content of Post request are created as follows: wstring wstrBoundry = L"--ABCD\r\n"; wstring wstrContent =wstrBoundry; wstrContent +=L"Content-Disposition: form-data; name=\"api_key\"\r\n\r\n"; wstrContent +=wstrAPIKey.c_str() ; wstrContent += L"\r\n"; wstrContent +=wstrBoundry; wstrContent +=L"Content-Disposition: form-data; name=\"auth_token\"\r\n\r\n"; wstrContent +=m_wstrToken.c_str(); wstrContent += L"\r\n"; wstrContent +=wstrBoundry; wstrContent +=L"Content-Disposition: form-data; name=\"api_sig\"\r\n\r\n"; wstrContent +=wstrSig; wstrContent += L"\r\n"; wstrContent +=wstrBoundry; wstrContent +=L"Content-Disposition: form-data; name=\"photo\"; filename=\"C:\\test.jpg\""; wstrContent +=L"\r\n"; wstrContent +=L"Content-Type: image/jpeg\r\n\r\n"; wstring wstrFilePath(L"C:\\test.jpg"); CAtlFile file; HRESULT hr = S_OK; hr = file.Create(wstrFilePath.c_str(),GENERIC_READ,FILE_SHARE_READ,OPEN_EXISTING); if(FAILED(hr)) { return; } ULONGLONG nLen; hr = file.GetSize(nLen); if (nLen > (DWORD)-1) { return ; } char * fileBuf = new char[nLen]; file.Read(fileBuf,nLen); wstring wstrLastLine(L"\r\n--ABCD--\r\n"); size_t szTotalSize = sizeof(wchar_t) * (wstrContent.length()) +sizeof(wchar_t) * (wstrLastLine.length()) + nLen; unsigned char *buffer = (unsigned char *)malloc(szTotalSize); memset(buffer,0,szTotalSize); memcpy(buffer,wstrContent.c_str(),wstrContent.length() * sizeof(wchar_t)); memcpy(buffer+wstrContent.length() * sizeof(wchar_t),fileBuf,nLen); memcpy(buffer+wstrContent.length() * sizeof(wchar_t)+nLen,wstrLastLine.c_str(),wstrLastLine.length() * sizeof(wchar_t)); hRequest = HttpOpenRequest(hSession, L"POST", L"/services/upload/", L"HTTP/1.1", NULL, NULL, 0, NULL); if(hRequest) { bRet = HttpAddRequestHeaders(hRequest,wstrAddHeaders.c_str(),wstrAddHeaders.length(),HTTP_ADDREQ_FLAG_ADD | HTTP_ADDREQ_FLAG_REPLACE); if(bRet) { bRet = HttpSendRequest(hRequest,NULL,0,(void *)buffer,szTotalSize); if(bRet) { while(true) { char buffer[1024]={0}; DWORD read=0; BOOL r = InternetReadFile(hRequest,buffer,1024,&read); if(read !=0) { wstring strUploadXML =buffer; break; } } } } I am not pretty sure the way I am adding image data to the string and posting the request. Do I need to convert image data into Unicode? Any suggestions , if someone can find what I am doing wrong that would be very helpful to me.

    Read the article

  • [C++] Adding a string or char array to a byte vector

    - by xeross
    I'm currently working on a class to create and read out packets send through the network, so far I have it working with 16bit and 8bit integers (Well unsigned but still). Now the problem is I've tried numerous ways of copying it over but somehow the _buffer got mangled, it segfaulted, or the result was wrong. I'd appreciate if someone could show me a working example. My current code can be seen below. Thanks, Xeross Main #include <iostream> #include <stdio.h> #include "Packet.h" using namespace std; int main(int argc, char** argv) { cout << "#################################" << endl; cout << "# Internal Use Only #" << endl; cout << "# Codename PACKETSTORM #" << endl; cout << "#################################" << endl; cout << endl; Packet packet = Packet(); packet.SetOpcode(0x1f4d); cout << "Current opcode is: " << packet.GetOpcode() << endl << endl; packet.add(uint8_t(5)) .add(uint16_t(4000)) .add(uint8_t(5)); for(uint8_t i=0; i<10;i++) printf("Byte %u = %x\n", i, packet._buffer[i]); printf("\nReading them out: \n1 = %u\n2 = %u\n3 = %u\n4 = %s", packet.readUint8(), packet.readUint16(), packet.readUint8()); return 0; } Packet.h #ifndef _PACKET_H_ #define _PACKET_H_ #include <iostream> #include <vector> #include <stdio.h> #include <stdint.h> #include <string.h> using namespace std; class Packet { public: Packet() : m_opcode(0), _buffer(0), _wpos(0), _rpos(0) {} Packet(uint16_t opcode) : m_opcode(opcode), _buffer(0), _wpos(0), _rpos(0) {} uint16_t GetOpcode() { return m_opcode; } void SetOpcode(uint16_t opcode) { m_opcode = opcode; } Packet& add(uint8_t value) { if(_buffer.size() < _wpos + 1) _buffer.resize(_wpos + 1); memcpy(&_buffer[_wpos], &value, 1); _wpos += 1; return *this; } Packet& add(uint16_t value) { if(_buffer.size() < _wpos + 2) _buffer.resize(_wpos + 2); memcpy(&_buffer[_wpos], &value, 2); _wpos += 2; return *this; } uint8_t readUint8() { uint8_t result = _buffer[_rpos]; _rpos += sizeof(uint8_t); return result; } uint16_t readUint16() { uint16_t result; memcpy(&result, &_buffer[_rpos], sizeof(uint16_t)); _rpos += sizeof(uint16_t); return result; } uint16_t m_opcode; std::vector<uint8_t> _buffer; protected: size_t _wpos; // Write position size_t _rpos; // Read position }; #endif // _PACKET_H_

    Read the article

  • where is the error in this C code , and how to get rid of the warnings?

    - by mekasperasky
    #include<stdio.h> #include<string.h> //This program is a sorting application that reads a sequence of numbers from a file and prints them on the screen . The reading from the file here , is a call back function . typedef int (*CompFunc)(const char* , const char* ); typedef int (*ReadCheck)(char nullcheck); char array[100]; //Let this fucntion be done in the library itself . It doesnt care as to where the compare function and how is it implemented . Meaning suppose the function wants to do sort in ascending order or in descending order then the changes have to be done by the client code in the "COMPARE" function who will be implementing the lib code . void ReadFile(FILE *fp,ReadCheck rc) { char a; char d[100]; int count = 0,count1=0; a=fgetc(fp); while(1 != (*rc)(a)) { if(a=='\0') { strcpy(array[count],d); count=count+1; } else { d[count1]=a; count1=count1+1; } } } void Bubblesort(int* array , int size , int elem_size , CompFunc cf) { int i,j; int *temp; for( i=0;i < size ;i++) { for ( j=0;j < size -1 ; j++) { // make the callback to the comparision function if(1 == (*cf)(array+j*elem_size,array+ (j+1)*elem_size)) { //interchanging of elements temp = malloc(sizeof(int *) * elem_size); memcpy(temp , array+j*elem_size,elem_size); memcpy(array+j*elem_size,array+(j+1)*elem_size,elem_size); memcpy(array + (j+1)*elem_size , temp , elem_size); free(temp); } } } } //Let these functions be done at the client side int Compare(const char* el1 , const char* el2) { int element1 = *(int*)el1; int element2 = *(int*)el2; if(element1 < element2 ) return -1; if(element1 > element2) return 1 ; return 0; } int ReadChecked(char nullcheck) { if (nullcheck=='\n') return 1; else return 0; } int main() { FILE fp1; int k; fp1=fopen("readdata.txt","r"); Readfile(fp1,&ReadChecked); Bubblesort((char*)array,5,sizeof(array[0]),&Compare); printf("after sorting \n"); for (k=0;k<5;k++) printf("%d",array[k]); return 0; } The error i get is fsc1.c: In function ‘ReadFile’: fsc1.c:19: warning: passing argument 1 of ‘strcpy’ makes pointer from integer without a cast fsc1.c: In function ‘Bubblesort’: fsc1.c:40: warning: passing argument 1 of ‘cf’ from incompatible pointer type fsc1.c:40: warning: passing argument 2 of ‘cf’ from incompatible pointer type fsc1.c:43: warning: incompatible implicit declaration of built-in function ‘malloc’ fsc1.c:47: warning: incompatible implicit declaration of built-in function ‘free’ fsc1.c: In function ‘main’: fsc1.c:80: error: incompatible types in assignment fsc1.c:82: warning: passing argument 1 of ‘Bubblesort’ from incompatible pointer type

    Read the article

  • Basic C question, concerning memory allocation and value assignment

    - by VHristov
    Hi there, I have recently started working on my master thesis in C that I haven't used in quite a long time. Being used to Java, I'm now facing all kinds of problems all the time. I hope someone can help me with the following one, since I've been struggling with it for the past two days. So I have a really basic model of a database: tables, tuples, attributes and I'm trying to load some data into this structure. Following are the definitions: typedef struct attribute { int type; char * name; void * value; } attribute; typedef struct tuple { int tuple_id; int attribute_count; attribute * attributes; } tuple; typedef struct table { char * name; int row_count; tuple * tuples; } table; Data is coming from a file with inserts (generated for the Wisconsin benchmark), which I'm parsing. I have only integer or string values. A sample row would look like: insert into table values (9205, 541, 1, 1, 5, 5, 5, 5, 0, 1, 9205, 10, 11, 'HHHHHHH', 'HHHHHHH', 'HHHHHHH'); I've "managed" to load and parse the data and also to assign it. However, the assignment bit is buggy, since all values point to the same memory location, i.e. all rows look identical after I've loaded the data. Here is what I do: char value[10]; // assuming no value is longer than 10 chars int i, j, k; table * data = (table*) malloc(sizeof(data)); data->name = "table"; data->row_count = number_of_lines; data->tuples = (tuple*) malloc(number_of_lines*sizeof(tuple)); tuple* current_tuple; for(i=0; i<number_of_lines; i++) { current_tuple = &data->tuples[i]; current_tuple->tuple_id = i; current_tuple->attribute_count = 16; // static in our system current_tuple->attributes = (attribute*) malloc(16*sizeof(attribute)); for(k = 0; k < 16; k++) { current_tuple->attributes[k].name = attribute_names[k]; // for int values: current_tuple->attributes[k].type = DB_ATT_TYPE_INT; // write data into value-field int v = atoi(value); current_tuple->attributes[k].value = &v; // for string values: current_tuple->attributes[k].type = DB_ATT_TYPE_STRING; current_tuple->attributes[k].value = value; } // ... } While I am perfectly aware, why this is not working, I can't figure out how to get it working. I've tried following things, none of which worked: memcpy(current_tuple->attributes[k].value, &v, sizeof(int)); This results in a bad access error. Same for the following code (since I'm not quite sure which one would be the correct usage): memcpy(current_tuple->attributes[k].value, &v, 1); Not even sure if memcpy is what I need here... Also I've tried allocating memory, by doing something like: current_tuple->attributes[k].value = (int *) malloc(sizeof(int)); only to get "malloc: * error for object 0x100108e98: incorrect checksum for freed object - object was probably modified after being freed." As far as I understand this error, memory has already been allocated for this object, but I don't see where this happened. Doesn't the malloc(sizeof(attribute)) only allocate the memory needed to store an integer and two pointers (i.e. not the memory those pointers point to)? Any help would be greatly appreciated! Regards, Vassil

    Read the article

  • How change LOD in geometry?

    - by ChaosDev
    Im looking for simple algorithm of LOD, for change geometry vertexes and decrease frame time. Im created octree, but now I want model or terrain vertex modify algorithm,not for increase(looking on tessellation later) but for decrease. I want something like this Questions: Is same algorithm can apply either to model and terrain correctly? Indexes need to be modified ? I must use octree or simple check distance between camera and object for desired effect ? New value of indexcount for DrawIndexed function needed ? Code: //m_LOD == 10 in the beginning //m_RawVerts - array of 3d Vector filled with values from vertex buffer. void DecreaseLOD() { m_LOD--; if(m_LOD<1)m_LOD=1; RebuildGeometry(); } void IncreaseLOD() { m_LOD++; if(m_LOD>10)m_LOD=10; RebuildGeometry(); } void RebuildGeometry() { void* vertexRawData = new byte[m_VertexBufferSize]; void* indexRawData = new DWORD[m_IndexCount]; auto context = mp_D3D->mp_Context; D3D11_MAPPED_SUBRESOURCE data; ZeroMemory(&data,sizeof(D3D11_MAPPED_SUBRESOURCE)); context->Map(mp_VertexBuffer->mp_buffer,0,D3D11_MAP_READ,0,&data); memcpy(vertexRawData,data.pData,m_VertexBufferSize); context->Unmap(mp_VertexBuffer->mp_buffer,0); context->Map(mp_IndexBuffer->mp_buffer,0,D3D11_MAP_READ,0,&data); memcpy(indexRawData,data.pData,m_IndexBufferSize); context->Unmap(mp_IndexBuffer->mp_buffer,0); DWORD* dwI = (DWORD*)indexRawData; int sz = (m_VertexStride/sizeof(float));//size of vertex element //algorithm must be here. std::vector<Vector3d> vertices; int i = 0; for(int j = 0; j < m_VertexCount; j++) { float x1 = (((float*)vertexRawData)[0+i]); float y1 = (((float*)vertexRawData)[1+i]); float z1 = (((float*)vertexRawData)[2+i]); Vector3d lv = Vector3d(x1,y1,z1); //my useless attempts if(j+m_LOD+1<m_RawVerts.size()) { float v1 = VECTORHELPER::Distance(m_RawVerts[dwI[j]],m_RawVerts[dwI[j+m_LOD]]); float v2 = VECTORHELPER::Distance(m_RawVerts[dwI[j]],m_RawVerts[dwI[j+m_LOD+1]]); if(v1>v2) lv = m_RawVerts[dwI[j+1]]; else if(v2<v1) lv = m_RawVerts[dwI[j+2]]; } (((float*)vertexRawData)[0+i]) = lv.x; (((float*)vertexRawData)[1+i]) = lv.y; (((float*)vertexRawData)[2+i]) = lv.z; i+=sz;//pass others vertex format values without change } for(int j = 0; j < m_IndexCount; j++) { //indices ? } //set vertexes to device UpdateVertexes(vertexRawData,mp_VertexBuffer->getSize()); delete[] vertexRawData; delete[] indexRawData; }

    Read the article

  • Why do my pyramids fade black and then back to colour again

    - by geminiCoder
    I have the following vertecies and norms GLfloat verts[36] = { -0.5, 0, 0.5, 0, 0, -0.5, 0.5, 0, 0.5, 0, 0, -0.5, 0.5, 0, 0.5, 0, 1, 0, -0.5, 0, 0.5, 0, 0, -0.5, 0, 1, 0, 0.5, 0, 0.5, -0.5, 0, 0.5, 0, 1, 0 }; GLfloat norms[36] = { 0, -1, 0, 0, -1, 0, 0, -1, 0, -1, 0.25, 0.5, -1, 0.25, 0.5, -1, 0.25, 0.5, 1, 0.25, -0.5, 1, 0.25, -0.5, 1, 0.25, -0.5, 0, -0.5, -1, 0, -0.5, -1, 0, -0.5, -1 }; I am writing my fists Open GL game, But I need to know for sure if my Normals are correct as the colours aren't rendering correctly. my Pyramids are coloured then fade to black every half rotation then back again. My app so far is based on the boiler plate code provided by apple. heres my modified setUp Method [EAGLContext setCurrentContext:self.context]; [self loadShaders]; self.effect = [[GLKBaseEffect alloc] init]; self.effect.light0.enabled = GL_TRUE; self.effect.light0.diffuseColor = GLKVector4Make(1.0f, 0.4f, 0.4f, 1.0f); glEnable(GL_DEPTH_TEST); glGenVertexArraysOES(1, &_vertexArray); //create vertex array glBindVertexArrayOES(_vertexArray); glGenBuffers(1, &_vertexBuffer); glBindBuffer(GL_ARRAY_BUFFER, _vertexBuffer); glBufferData(GL_ARRAY_BUFFER, sizeof(verts) + sizeof(norms), NULL, GL_STATIC_DRAW); //create vertex buffer big enough for both verts and norms and pass NULL as data.. uint8_t *ptr = (uint8_t *)glMapBufferOES(GL_ARRAY_BUFFER, GL_WRITE_ONLY_OES); //map buffer to pass data to it memcpy(ptr, verts, sizeof(verts)); //copy verts memcpy(ptr+sizeof(verts), norms, sizeof(norms)); //copy norms to position after verts glUnmapBufferOES(GL_ARRAY_BUFFER); glEnableVertexAttribArray(GLKVertexAttribPosition); glVertexAttribPointer(GLKVertexAttribPosition, 3, GL_FLOAT, GL_FALSE, 0, BUFFER_OFFSET(0)); //tell GL where verts are in buffer glEnableVertexAttribArray(GLKVertexAttribNormal); glVertexAttribPointer(GLKVertexAttribNormal, 3, GL_FLOAT, GL_FALSE, 0, BUFFER_OFFSET(sizeof(verts))); //tell GL where norms are in buffer glBindVertexArrayOES(0); And the update method. - (void)update { float aspect = fabsf(self.view.bounds.size.width / self.view.bounds.size.height); GLKMatrix4 projectionMatrix = GLKMatrix4MakePerspective(GLKMathDegreesToRadians(65.0f), aspect, 0.1f, 100.0f); self.effect.transform.projectionMatrix = projectionMatrix; GLKMatrix4 baseModelViewMatrix = GLKMatrix4MakeTranslation(0.0f, 0.0f, -4.0f); baseModelViewMatrix = GLKMatrix4Rotate(baseModelViewMatrix, _rotation, 0.0f, 1.0f, 0.0f); // Compute the model view matrix for the object rendered with GLKit GLKMatrix4 modelViewMatrix = GLKMatrix4MakeTranslation(0.0f, 0.0f, -1.5f); modelViewMatrix = GLKMatrix4Rotate(modelViewMatrix, _rotation, 1.0f, 1.0f, 1.0f); modelViewMatrix = GLKMatrix4Multiply(baseModelViewMatrix, modelViewMatrix); self.effect.transform.modelviewMatrix = modelViewMatrix; // Compute the model view matrix for the object rendered with ES2 modelViewMatrix = GLKMatrix4MakeTranslation(0.0f, 0.0f, 1.5f); modelViewMatrix = GLKMatrix4Rotate(modelViewMatrix, _rotation, 1.0f, 1.0f, 1.0f); modelViewMatrix = GLKMatrix4Multiply(baseModelViewMatrix, modelViewMatrix); _normalMatrix = GLKMatrix3InvertAndTranspose(GLKMatrix4GetMatrix3(modelViewMatrix), NULL); _modelViewProjectionMatrix = GLKMatrix4Multiply(projectionMatrix, modelViewMatrix); _rotation += self.timeSinceLastUpdate * 0.5f; } But providing I understand this correct one pyramid is using the GLKit base effect shaders and the other the shaders which are included in the project. So for both of them to have the same error, I thought it would be the Norms?

    Read the article

  • DirectX particle system. ConstantBuffer

    - by Liuka
    I'm new in DirectX and I'm making a 2D game. I want to use a particle system to simulate a 3D starfield, so each star has to set its own constant buffer for the vertexshader es. to set it's world matrix. So if i have 500 stars (that move every frame) i need to call 500 times VSsetconstantbuffer, and map/unmap each buffer. with 500 stars i have an average of 220 fps and that's quite good. My bottelneck is Vs/PsSetconstantbuffer. If i dont call this function i have 400 fps(obliviously nothing is display, since i dont set the position of the stars). So is there a method to speed up the render of the particle system?? Ps. I'm using intel integrate graphic (hd 2000-3000). with a nvidia (or amd) gpu will i have the same bottleneck?? If, for example, i dont call setshaderresource i have 10-20 fps more (for 500 objcets), that is not 180.Why does SetConstantBuffer take so long?? LPVOID VSdataPtr = VSmappedResource.pData; memcpy(VSdataPtr, VSdata, CszVSdata); context->Unmap(VertexBuffer, 0); result = context->Map(PixelBuffer, 0, D3D11_MAP_WRITE_DISCARD, 0, &PSmappedResource); if (FAILED(result)) { outputResult.OutputErrorMessage(TITLE, L"Cannot map the PixelBuffer", &result, OUTPUT_ERROR_FILE); return; } LPVOID PSdataPtr = PSmappedResource.pData; memcpy(PSdataPtr, PSdata, CszPSdata); context->Unmap(PixelBuffer, 0); context->VSSetConstantBuffers(0, 1, &VertexBuffer); context->PSSetConstantBuffers(0, 1, &PixelBuffer); this update and set the buffer. It's part of the render method of a sprite class that contains a the vertex buffer and the texture to apply to the quads(it's a 2d game) too. I have an array of 500 stars (sprite setup with a star texture). Every frame: clear back buffer; draw the array of stars; present the backbuffer; draw also call the function update( which calculate the position of the sprite on screen based on a "camera class") Ok, create a vertex buffer with the vertices of each quads(stars) seems to be good, since the stars don't change their "virtual" position; so.... In a particle system (where particles move) it's better to have all the object in only one vertices array, rather then an array of different sprite/object in order to update all the vertices' position with a single setbuffer call. In this case i have to use a dynamic vertex buffer with the vertices positions like this: verticesForQuad={{ XMFLOAT3((float)halfDImensions.x-1+pos.x, (float)halfDImensions.y-1+pos.y, 1.0f), XMFLOAT2(1.0f, 0.0f) }, { XMFLOAT3((float)halfDImensions.x-1+pos.x, -(float)halfDImensions.y-1+pos.y, 1.0f), XMFLOAT2(1.0f, 1.0f) }, { XMFLOAT3(-(float)halfDImensions.x-1+pos.x, (float)halfDImensions.y-1.pos.y, 1.0f), XMFLOAT2(0.0f, 0.0f) }, { XMFLOAT3(-(float)halfDImensions.x-1.pos.x, -(float)halfDImensions.y-1+pos.y, 1.0f), XMFLOAT2(0.0f, 1.0f) }, ....other quads} where halfDimensions is the halfsize in pixel of a texture and pos the virtual position of a star. than create an array of verticesForQuad and create the vertex buffer ZeroMemory(&vertexDesc, sizeof(vertexDesc)); vertexDesc.Usage = D3D11_USAGE_DEFAULT; vertexDesc.BindFlags = D3D11_BIND_VERTEX_BUFFER; vertexDesc.ByteWidth = sizeof(VertexType)* 4*numStars; ZeroMemory(&resourceData, sizeof(resourceData)); resourceData.pSysMem = verticesForQuad; result = device->CreateBuffer(&vertexDesc, &resourceData, &CvertexBuffer); and call each frame Context->IASetVertexBuffers(0, 1, &CvertexBuffer, &stride, &offset); But if i want to add and remove obj i have to recreate the buffer each time, havent i?? There is a faster way? I think i can create a vertex buffer with a max size (es. 10000 objs) and when i update it set only the 250 position (for 250 onjs for example) and pass this number as the vertexCount to the draw function (numObjs*4), or i'm worng

    Read the article

< Previous Page | 1 2 3 4 5 6 7  | Next Page >