Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
440 views
in Technique[技术] by (71.8m points)

c++ - Copy number of bytes to a position in memory

If I am not correct, the codes following are used to copy an array of bytes to a position of memory in C#:

byte[] byteName = Encoding.ASCII.GetBytes("Hello There");

int positionMemory = getPosition();

Marshal.Copy(byteName, 0, new IntPtr(positionMemory), byteName.length);

How can I achieve this in native C++?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

use a pointer and memcpy:

void * memcpy ( void * destination, const void * source, size_t num );

Suppose you want to copy an array A of length n into an array B

memcpy (B, A, n * sizeof(char));

This is more C than C++, the string class have copy capabilities you can use.

  size_t length;
  char buffer[20];
  string str ("Test string...");
  length=str.copy(buffer,6,5);
  buffer[length]='';

Here's a more specific sample with a complete code:

#include <stdio.h>
#include <string>
#include <string.h>
#include <iostream>

using namespace std;
int main()
{

    string s("Hello World");
    char buffer [255];
    void * p = buffer; // Or void * p = getPosition()
    memcpy(p,s.c_str(),s.length()+1);
    cout << s << endl;
    cout << buffer << endl;
    return 0;
}

let me know if you need more details


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...